Wait() public method

public Wait ( System.TimeSpan ts ) : bool
ts System.TimeSpan
return bool
コード例 #1
0
        public void ExtremeDisposal()
        {
            using (var context = CreateContext())
            {
                Assert.AreEqual(-1, context.Publisher.MySettings.MaxConnectionRetry, "For this test, we want the worst situation");

                context.Publisher.Start(0);
                Assert.IsTrue(context.Publisher.Started);

                var message = new byte[] { 0, 1, 1 };
                var connectionFail = new SemaphoreSlim(0);
                context.Model.Setup(m => m.BasicPublish(It.IsAny<string>(), It.IsAny<string>(), context.Publisher.Props, message)).Throws(new Exception("I don't want your message anymore"));
                context.Connection.Setup(c => c.CreateModel()).Callback(() => connectionFail.Release(1)).Throws(new Exception("And I don't want to accept your connection either"));

                context.Publisher.Publish("test", message);

                /* The way callbacks are implemented on exception throwing mocks does not garantee
                 * that the callback is called "after" the exception is thrown.
                 * If we wait for two, we are sure at least one has been finished !
                 */
                Assert.IsTrue(connectionFail.Wait(1000));
                Assert.IsTrue(connectionFail.Wait(1000));

                context.Publisher.Dispose();
                context.Publisher = null; //to avoid the double dispose of Publisher
                //The real test here is that eventually the Dispose method returns
                Assert.Pass();
            }
        }
コード例 #2
0
        public void AsyncLockShouldAllowOnlyOneThread()
        {
            var block = new SemaphoreSlim(0, 2);
            var count = 0;
            var alock = new AsyncLock();

            var firstCall = Task.Factory.StartNew(async () =>
            {
                using (await alock.LockAsync())
                {
                    Interlocked.Increment(ref count);
                    block.Wait();
                }
                block.Wait();//keep this thread busy
            });

            TaskTest.WaitFor(() => count > 0);

            alock.LockAsync().ContinueWith(t => Interlocked.Increment(ref count));

            Assert.That(count, Is.EqualTo(1), "Only one task should have gotten past lock.");
            Assert.That(firstCall.IsCompleted, Is.False, "Task should still be running.");

            block.Release();
            TaskTest.WaitFor(() => count > 1);
            Assert.That(count, Is.EqualTo(2), "Second call should get past lock.");
            Assert.That(firstCall.IsCompleted, Is.False, "First call should still be busy.");
            block.Release();
        }
コード例 #3
0
ファイル: EngineBase.cs プロジェクト: bernharde/PortiLog
        public virtual void RegisterListener(ListenerBase listener)
        {
            semaphoreSlim.Wait();
            if (!_listeners.Contains(listener))
            {
                listener.Engine = this;
                _listeners.Add(listener);

                listener.DumpEnabled = DumpEnabled;

                InternalTrace(Entry.CreateInfo(string.Format("Listener '{0}' registered", listener.Name)));
            }
            semaphoreSlim.Release();
        }
コード例 #4
0
        public static void CancelBeforeWait()
        {
            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2);

            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(millisec, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(timeSpan, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            semaphoreSlim.Dispose();
        }
コード例 #5
0
        public void Construct_GivenSemaphoreSlim_ShouldLockIt()
        {
            //---------------Set up test pack-------------------
            using (var semaphore = new SemaphoreSlim(1))
            {
                bool? gotLock = null;
                //---------------Assert Precondition----------------
                using (new LenientAutoLocker(semaphore))
                {
                    var barrier = new Barrier(2);
                    Task.Run(() =>
                    {
                        barrier.SignalAndWait();
                        Thread.Sleep(1000);
                        // ReSharper disable once AccessToDisposedClosure
                        gotLock = semaphore.Wait(100);
                    });
                    //---------------Execute Test ----------------------
                    barrier.SignalAndWait();
                    Thread.Sleep(2000);

                    //---------------Test Result -----------------------
                    Assert.IsNotNull(gotLock);
                    Assert.IsFalse(gotLock.Value);
                }
            }
        }
コード例 #6
0
 public void TryDequeue_IfMustWaitForItem_ThenProvidesItAndReturnsTrue()
 {
     DoTest((q, cts) =>
     {
         using (var willProvideItemAfterSleep = new SemaphoreSlim(0))
         {
             var tasks = new Task[]
                 {
                     new Task(() =>
                         {
                             string item;
                             willProvideItemAfterSleep.Wait();
                             Assert.IsTrue(q.TryDequeue(out item, cts.Token));
                             Assert.AreEqual("7", item);
                         }),
                     new Task(() =>
                         {
                             willProvideItemAfterSleep.Release();
                             Thread.Sleep(500);
                             q.Enqueue(7);
                         })
                 };
             Parallel.ForEach<Task>(tasks, T => T.Start());
             Task.WaitAll(tasks);
         }
     });
 }
コード例 #7
0
ファイル: Program.cs プロジェクト: sdcb/fuck-iphone-stealer
        static void Main(string[] args)
        {
            Console.Write("request count(8 recommanded): ");
            var requestCount = int.Parse(Console.ReadLine());
            ServicePointManager.DefaultConnectionLimit = 10000;
            
            var alert = new AlertInSecond();

            var ss = new SemaphoreSlim(requestCount, requestCount);
            while (true)
            {
                ss.Wait();
                Task.Run(OneRequest).ContinueWith(t =>
                {
                    if (t.Status == TaskStatus.Faulted)
                    {
                        alert.AddOneFail();
                    }
                    else
                    {
                        var response = t.Result;
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            alert.AddOneSuccess();
                        }
                        else
                        {
                            alert.AddOneFail();
                        }
                    }
                    
                    ss.Release();
                });
            }
        }
コード例 #8
0
 static void TaskMain(SemaphoreSlim semaphore)
 {
     bool isCompleted = false;
       while (!isCompleted)
       {
     if (semaphore.Wait(600))
     {
       try
       {
     Console.WriteLine("Task {0} locks the semaphore", Task.CurrentId);
     Thread.Sleep(2000);
       }
       finally
       {
     Console.WriteLine("Task {0} releases the semaphore", Task.CurrentId);
     semaphore.Release();
     isCompleted = true;
       }
     }
     else
     {
       Console.WriteLine("Timeout for task {0}; wait again",
      Task.CurrentId);
     }
       }
 }
コード例 #9
0
 private static void TaskMain(SemaphoreSlim semaphore)
 {
     bool isCompleted = false;
     while (!isCompleted)
     {
         if (semaphore.Wait(600))
         {
             try
             {
                 WriteLine($"Task {Task.CurrentId} locks the semaphore");
                 Task.Delay(2000).Wait();
             }
             finally
             {
                 WriteLine($"Task {Task.CurrentId} releases the semaphore");
                 semaphore.Release();
                 isCompleted = true;
             }
         }
         else
         {
             WriteLine($"Timeout for task {Task.CurrentId}; wait again");
         }
     }
 }
コード例 #10
0
ファイル: ProducerTests.cs プロジェクト: jsifantu/kafka-net
        public void ProducerShouldReportCorrectAmountOfAsyncRequests()
        {
            var semaphore = new SemaphoreSlim(0);
            var routerProxy = new FakeBrokerRouter();
            //block the second call returning from send message async
            routerProxy.BrokerConn0.ProduceResponseFunction = () => { semaphore.Wait(); return new ProduceResponse(); };

            var router = routerProxy.Create();
            using (var producer = new Producer(router, maximumAsyncRequests: 1) { BatchSize = 1 })
            {
                var messages = new[] { new Message("1") };

                Assert.That(producer.AsyncCount, Is.EqualTo(0));

                var sendTask = producer.SendMessageAsync(BrokerRouterProxy.TestTopic, messages);

                TaskTest.WaitFor(() => producer.AsyncCount > 0);
                Assert.That(producer.AsyncCount, Is.EqualTo(1), "One async operation should be sending.");

                semaphore.Release();
                sendTask.Wait(TimeSpan.FromMilliseconds(500));

                Assert.That(sendTask.IsCompleted, Is.True, "Send task should be marked as completed.");
                Assert.That(producer.AsyncCount, Is.EqualTo(0), "Async should now show zero count.");
            }
        }
コード例 #11
0
        public void DeclareAndUseIt()
        {
            var channel = this.Connection.CreateChannel();
            var exchange = channel.DeclareExchange("my6exchange", new ExchangeOptions()
            {
                // using default options = ephemeral
                ExchangeType = RabbitExchangeType.Fanout
            });

            var queue1 = exchange.DeclareQueue("q1", new QueueOptions());
            var queue2 = exchange.DeclareQueue("q2", new QueueOptions());
            var wait = new SemaphoreSlim(2, 2);
            var receivedCount = 0;

            queue1.Consume(new Action<MessageEnvelope<MyDumbMessage>>(env =>
            {
                wait.Release();
                Interlocked.Increment(ref receivedCount);
            }), new ConsumerOptions());
            queue2.Consume(new Action<MessageEnvelope<MyDumbMessage>>(env =>
            {
                wait.Release();
                Interlocked.Increment(ref receivedCount);
            }), new ConsumerOptions());

            exchange.Send(new MyDumbMessage()); // message will be dropped

            wait.Wait(TimeSpan.FromSeconds(2.0));

            receivedCount.Should().Be(2);
        }
コード例 #12
0
        public static bool CancelAfterWait()
        {
            TestHarness.TestLog("* SemaphoreSlimCancellationTests.CancelAfterWait()");
            bool passed = true;

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0); // semaphore that will block all waiters
            
            ThreadPool.QueueUserWorkItem(
                (args) =>
                {
                    Thread.Sleep(1000);
                    cancellationTokenSource.Cancel();
                }
                );

            //Now wait.. the wait should abort and an exception should be thrown
            passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(
                () => semaphoreSlim.Wait(cancellationToken),
                cancellationToken, "An OCE(null) should have been thrown that references the cancellationToken.");

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually

            return passed;
        }
コード例 #13
0
ファイル: test489437.cs プロジェクト: CheneyWu/coreclr
    static int Main(string[] args)
    {
        SemaphoreSlim s = new SemaphoreSlim(initialCount: 1);

        var cts = new CancellationTokenSource();
        s.Wait();
        var t = s.WaitAsync(cts.Token);
        s.Release();
        cts.Cancel();


        if (t.Status != TaskStatus.Canceled && s.CurrentCount == 0)
        {
            Console.WriteLine("PASS");
            return 100;
        }
        else
        {
            Console.WriteLine("FAIL");
            Console.WriteLine("Expected task status to not be Canceled and s.CurrentCount == 0");
            Console.WriteLine("Actual: Task: " + t.Status + "; CurrentCount: " + s.CurrentCount);
            return 101;
        }


    }
コード例 #14
0
ファイル: Program.cs プロジェクト: c0ns0le/scripts-4
        private static void RunAndBlock(int threadCount)
        {
            ProfilerStart();
            _Semaphore = new SemaphoreSlim(threadCount, threadCount);

            var queue = new QueueClient();

            while (!_Cancel)
            {
                _Semaphore.Wait();
                var solicutud = queue.GetNextMessage();
                if (solicutud == null)
                {
                    Thread.Sleep(millisecondsTimeout: _NoMessageFoundSleepTimeoutMsec);
                }
                else
                {
                    var t = new Thread(new ParameterizedThreadStart(RunThreaded));
                    t.Start(solicutud);
                }
            }
            //Pause();

            // release threads
            ProfilerStop();
        }
コード例 #15
0
 public AwaitingConnectedSpheroRunner(IStreamSocketWrapper streamSpheroWrapper)
 {
     _streamSpheroWrapper = streamSpheroWrapper;
     _itemsToSendEvent = new SemaphoreSlim(1);
     _itemsToSendEvent.Wait();
     _commandsToSend = new Queue<CommandWithActions>();
 }
コード例 #16
0
ファイル: Metadata.cs プロジェクト: mamaar/Liftbridge.Net
 /// <summary>
 /// Removes the stream entry from the cache.
 /// </summary>
 public void RemoveStream(string stream)
 {
     Semaphore.Wait();
     MetadataData = MetadataData with {
         Streams = MetadataData.Streams.Remove(stream)
     };
     Semaphore.Release();
 }
コード例 #17
0
ファイル: SemaphoreLock.cs プロジェクト: 2a486f72/useful
		public static SemaphoreLock Take(SemaphoreSlim semaphore)
		{
			Argument.ValidateIsNotNull(semaphore, "semaphore");

			semaphore.Wait();

			return new SemaphoreLock(semaphore);
		}
コード例 #18
0
        public void ConcurrentSetsAndWaits__3()
        {
            var autoResSlim = new AutoResetSuperSlimLock(false);

            var obtainedEv = new AutoResetEvent(true);
            var barrier = new ManualResetEvent(false);
            var semaphore = new SemaphoreSlim(0, 4);

            int countOfObtained = 0;
            int countOfMissed = 0;
            var tasks = new List<Task>();

            for (int i = 0; i < 4; i++)
            {
                var t = Task.Factory.StartNew((p) =>
                {
                    barrier.WaitOne();

                    for (int j = 0; j < 1000; j++)
                    {
                        if (autoResSlim.Wait())
                        {
                            Interlocked.Increment(ref countOfObtained);
            //							Console.WriteLine(countOfObtained + " _ " + p);
                            obtainedEv.Set();
                        }
                        else
                        {
                            Interlocked.Increment(ref countOfMissed);
                        }
                    }

                    semaphore.Release();
                }, i);
                tasks.Add(t);
            }

            var t1 = Task.Factory.StartNew(() =>
            {
                barrier.Set();
                for (int i = 0; i < 4000; i++)
                {
                    obtainedEv.WaitOne();
                    autoResSlim.Set();
            //					Console.WriteLine("*\t" + i);
                }
            });
            tasks.Add(t1);

            Task.WaitAll(tasks.ToArray());

            for (int i = 0; i < 4; i++)
                semaphore.Wait();

            countOfObtained.Should().Be(4000);

            autoResSlim.IsSet.Should().BeFalse();
        }
コード例 #19
0
ファイル: SemaphoreLock.cs プロジェクト: 2a486f72/useful
		public static SemaphoreLock TryTake(SemaphoreSlim semaphore, TimeSpan timeout)
		{
			Argument.ValidateIsNotNull(semaphore, "semaphore");

			if (semaphore.Wait(timeout))
				return new SemaphoreLock(semaphore);
			else
				return null;
		}
コード例 #20
0
		public void CurrentCountMaxTestCase()
		{
			using (var semMax = new SemaphoreSlim(5, 5)) {
				semMax.Wait();
				try {
					semMax.Release(3);
					Assert.Fail ();
				} catch (SemaphoreFullException) {}
			}
		}
コード例 #21
0
        public void constructor_should_initialize_instance_with_incompleted_task_when_semaphore_is_not_available()
        {
            var semaphore = new SemaphoreSlim(1);
            semaphore.Wait();

            var result = new SemaphoreSlimRequest(semaphore, CancellationToken.None);

            result.Task.IsCompleted.Should().BeFalse();
            semaphore.CurrentCount.Should().Be(0);
        }
コード例 #22
0
ファイル: Logic.cs プロジェクト: ryanechternacht/Niya
        public static RowCol NextMove(Board board, IPlayer me, IPlayer opp)
        {
            // this is similar to of MyMove but with logging and multithreading

            var moves = new Dictionary<RowCol, int> ();
            var legalMoves = board.GetLegalMoves ();

            int count = 0;
            Console.WriteLine ("Starting move assessment ({0} to assess)", legalMoves.Count ());
            var semaphore = new SemaphoreSlim (4);
            var tasks = new Task[legalMoves.Count ()];
            foreach (var move in legalMoves)
            {
                var count1 = ++count;
                tasks[count1-1] = Task.Run (() =>
                {
                    semaphore.Wait();
                    Console.WriteLine ("{0} starting (option {1}/{2})", move, count1, legalMoves.Count ());

                    var b = board.Play (me, move);

                    var isGameOver = b.IsGameOver (me);
                    int value;
                    if (isGameOver == GameEnd.Win)
                        value = int.MaxValue; // if we can win, take it now!
                    else if (isGameOver == GameEnd.Tie)
                        value = 0;
                    else
                        value = OppMove (b, me, opp);

                    moves [move] = value;

                    Console.WriteLine ("{0} scores {1} (option {2}/{3})", move, value, count1, legalMoves.Count ());
                    semaphore.Release();
                });
            }
            Task.WaitAll (tasks);

            var bestMove = null as RowCol;
            int best = -1;
            foreach (var kvp in moves)
                if (kvp.Value > best)
                {
                    best = kvp.Value;
                    bestMove = kvp.Key;
                }
            if (bestMove != null)
                Console.WriteLine ("The best move is {0}, with a score of {1}", bestMove, best);
            else
            {
                Console.WriteLine ("All moves should result in losing, choosing randomly");
                bestMove = legalMoves [new Random ().Next (legalMoves.Count)];
            }
            return bestMove;
        }
コード例 #23
0
        public void Execute()
        {
            //
            // SemaphoreSlimのWaitメソッドにはキャンセルトークンを
            // 受け付けるオーバーロードが存在する。
            //
            // CountdownEventやBarrierの場合と同じく、Waitメソッドに
            // キャンセルトークンを指定した場合、別の場所にてキャンセルが
            // 行われると、OperationCanceledExceptionが発生する。
            //
            const int timeout = 2000;

            var tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;

            using (var semaphore = new SemaphoreSlim(2))
            {
                //
                // あらかじめ、セマフォの上限までWaitしておき
                // 後のスレッドが入れないようにしておく.
                //
                semaphore.Wait();
                semaphore.Wait();

                //
                // 3つのタスクを作成する.
                //  1つ目のタスク:キャンセルトークンを指定して無制限待機.
                //  2つ目のタスク:キャンセルトークンとタイムアウト値を指定して待機.
                //  3つ目のタスク:特定時間待機した後、キャンセル処理を行う.
                //
                Parallel.Invoke
                (
                    () => WaitProc1(semaphore, token),
                    () => WaitProc2(semaphore, timeout, token),
                    () => DoCancel(timeout, tokenSource)
                );

                semaphore.Release();
                semaphore.Release();
                Output.WriteLine("CurrentCount={0}", semaphore.CurrentCount);
            }
        }
コード例 #24
0
        public void Foo(Action printFoo)
        {
            for (int i = 0; i < n; i++)
            {
                slim1.Wait();
                // printFoo() outputs "foo". Do not change or remove this line.
                printFoo();

                slim2.Release();
            }
        }
コード例 #25
0
        public static bool CancelBeforeWait()
        {
            TestHarness.TestLog("* SemaphoreSlimCancellationTests.CancelBeforeWait()");
            bool passed = true;

            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2);
            
            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);
            passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(ct), ct, "An OCE should have been thrown.");
            passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(millisec, ct), ct, "An OCE should have been thrown.");
            passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(timeSpan, ct), ct, "An OCE should have been thrown.");
            semaphoreSlim.Dispose();

            return passed;
        }
コード例 #26
0
        public void Dispose_should_cancel_pending_request()
        {
            var semaphore = new SemaphoreSlim(1);
            semaphore.Wait();
            var subject = new SemaphoreSlimRequest(semaphore, CancellationToken.None);

            subject.Dispose();
            semaphore.Release();

            subject.Task.Status.Should().Be(TaskStatus.Canceled);
            semaphore.CurrentCount.Should().Be(1);
        }
コード例 #27
0
        public void ConcurrentEmitsReachForEach()
        {
            var count = 100;
            var howOften = 1000;

            var source = AsyncEnumerable.Source<int>();
            var evt = new ManualResetEventSlim();
            var sem = new SemaphoreSlim(0);

            var derived = source.Select(i => i).Where(i => true);

            var values = new HashSet<int>();
            var subscription = source.ForEach(i =>
            {
                lock (values)
                {
                    values.Add(i);
                }
            });


            for (int i = 0; i < count; i++)
            {
                var id = i;
                var t = new Thread(() =>
                {
                    evt.Wait();
                    for(int x = 0; x < howOften; x++)
                        source.Yield(id).Wait();
                    sem.Release();
                });
                t.IsBackground = true;
                t.Start();
            }

            evt.Set();

            for (int i = 0; i < count; i++)
                sem.Wait();

            var arr = values.OrderBy(a => a).ToArray();

            Assert.AreEqual(count, arr.Length, "not all inputs processed");

            for (int i = 0; i < count; i++)
            {
                Assert.AreEqual(i, arr[i]);
            }



        }
コード例 #28
0
 public void WaitRelease()
 {
     using (var semaphore = new SemaphoreSlim(2, 2))
     {
         var stopwatch = Stopwatch.StartNew();
         for (var i = 0; i < Iterations; i++)
         {
             semaphore.Wait();
             semaphore.Release();
         }
         stopwatch.StopAndLog(Iterations);
     }
 }
コード例 #29
0
ファイル: Resumable.cs プロジェクト: senghuot/resumable
 // uploading all the chunks into grid.fs.files asynchronously but we have to watch out for
 // resource competition. so we will only allow upto 'simultaneousUploads' tasks run at a time.
 // this ensure that gridfs to not overwhelm with write requests.
 public void multiThreadedUpload(List<byte[]> chunks, string id, MongoGridFS grid)
 {
     SemaphoreSlim max = new SemaphoreSlim(simultaneousUploads);
     var tasks = new Task[chunks.Count];
     for (var i = 0; i < chunks.Count; i++) {
         max.Wait();
         var index = i;
         var chunkMetadata = new BsonDocument { { "files_id", new ObjectId(id) }, { "n", i }, { "data", chunks[i] } };
         tasks[i] = Task.Factory.StartNew(() => writeToGrid(chunkMetadata, grid, index)
             , TaskCreationOptions.LongRunning)
             .ContinueWith( (task) => max.Release());
     }
     Task.WaitAll(tasks);
 }
コード例 #30
0
        public void Test()
        {
            SemaphoreSlim ss = new SemaphoreSlim(2); // se le indica que el thread se detendra 2 veces.
            Debug.Print("Constructed a SemaphoreSlim with an initial count of 2");

            Debug.Print("First non-blocking Wait: {0} (should be true)", ss.Wait(0));//la primera vez que espera por 0 milisegundos.
            Debug.Print("Second non-blocking Wait: {0} (should be true)", ss.Wait(0));//la segunda vez.
            Debug.Print("Third non-blocking Wait: {0} (should be false)", ss.Wait(0));//aqui ya no se espera, aunque se haga wait, porque solo son dos veces.

            // Do a Release to free up a spot
            ss.Release();//con Release se puede esperar una vez mas a parte de las que ya tenia programadas.regresa un thread otra vez al pool., tenia 2 segun el constructor.

            Debug.Print("Non-blocking Wait after Release: {0} (should be true)", ss.Wait(0));

            // Launch an asynchronous Task that releases the semaphore after 100 ms..asynchronous significa en otro hilo.
            Task t1 = Task.Factory.StartNew(() =>
            {
                Thread.Sleep(100);
                Debug.Print("Task about to release SemaphoreSlim");
                ss.Release();
            });

            // You can also wait on the SemaphoreSlim via the underlying Semaphore WaitHandle.
            // HOWEVER, unlike SemaphoreSlim.Wait(), it WILL NOT decrement the count.
            // In the printout below, you will see that CurrentCount is still 1
            ss.AvailableWaitHandle.WaitOne();
            Debug.Print("ss.AvailableWaitHandle.WaitOne() returned, ss.CurrentCount = {0}", ss.CurrentCount);

            // Now a real Wait(), which should return immediately and decrement the count.
            ss.Wait();
            Debug.Print("ss.CurrentCount after ss.Wait() = {0}", ss.CurrentCount);

            // Clean up
            t1.Wait();
            ss.Dispose();
        }
コード例 #31
0
ファイル: Program.cs プロジェクト: sdao/mb-device-tcp
        static void Main(string[] args)
        {
            TcpListener orClientListener = new TcpListener(IPAddress.Any, 3001);
            orClientListener.Start();

            TcpListener phoneListener = new TcpListener(IPAddress.Any, 3002);
            phoneListener.Start();

            Console.WriteLine("Server online.");

            OpenRealityLoop(orClientListener);
            PhoneLoop(phoneListener);

            SemaphoreSlim sema = new SemaphoreSlim(0);
            sema.Wait();
        }
コード例 #32
0
ファイル: SyncPrimitives.cs プロジェクト: YoeriVD/ADCSBDEMOS
 public void Semaphore()
 {
     var range = Enumerable.Range(0, 10).ToList();
     var sem = new SemaphoreSlim(2);
     Parallel.ForEach(range, i =>
     {
         sem.Wait();
         Console.WriteLine($"Current sem count after wait of {i} : {sem.CurrentCount}");
         Task.Run(() =>
         {
             Thread.Sleep(500);
             sem.Release();
             Console.WriteLine($"Current sem count after release of {i} : {sem.CurrentCount}");
         });
     });
     Console.WriteLine("done");
 }
コード例 #33
0
        public void Run(Action action)
        {
            _semaphore.Wait();

            Task.Factory.StartNew(() =>
            {
                try
                {
                    // This task pool is used for jobs only, so the actions are guaranteed to not throw exceptions
                    action();
                }
                finally
                {
                    _semaphore.Release();
                }
            });
        }
コード例 #34
0
        static void Main(string[] args)
        {
            // create the primtive
            SemaphoreSlim semaphore = new SemaphoreSlim(2);

            // create the cancellation token source
            CancellationTokenSource tokenSource
                = new CancellationTokenSource();

            // create and start the task that will wait on the event
            for (int i = 0; i < 10; i++) {
                Task.Factory.StartNew(() => {
                    while (true) {
                        semaphore.Wait(tokenSource.Token);
                        // print out a message when we are released
                        Console.WriteLine("Task {0} released", Task.CurrentId);
                    }
                }, tokenSource.Token);
            }

            // create and start the signalling task
            Task signallingTask = Task.Factory.StartNew(() => {
                // loop while the task has not been cancelled
                while (!tokenSource.Token.IsCancellationRequested) {
                    // go to sleep for a random period
                    tokenSource.Token.WaitHandle.WaitOne(500);
                    // signal the semaphore
                    semaphore.Release(2);
                    Console.WriteLine("Semaphore released");
                }
                // if we reach this point, we know the task has been cancelled
                tokenSource.Token.ThrowIfCancellationRequested();
            }, tokenSource.Token);

            // ask the user to press return before we cancel
            // the token and bring the tasks to an end
            Console.WriteLine("Press enter to cancel tasks");
            Console.ReadLine();

            // cancel the token source and wait for the tasks
            tokenSource.Cancel();

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }
コード例 #35
0
        static async Task Main(string[] args)
        {
            // Create the semaphore.
            semaphore = new System.Threading.SemaphoreSlim(0, 3);
            Console.WriteLine("{0} tasks can enter the semaphore.",
                              semaphore.CurrentCount);
            Task[] tasks = new Task[5];

            // Create and start five numbered tasks.
            for (int i = 0; i <= 4; i++)
            {
                tasks[i] = Task.Run(() => {
                    // Each task begins by requesting the semaphore.
                    Console.WriteLine("Task {0} begins and waits for the semaphore.",
                                      Task.CurrentId);
                    semaphore.Wait();

                    Interlocked.Add(ref padding, 100);

                    Console.WriteLine("Task {0} enters the semaphore.", Task.CurrentId);

                    // The task just sleeps for 1+ seconds.
                    Thread.Sleep(1000 + padding);

                    Console.WriteLine("Task {0} releases the semaphore; previous count: {1}.",
                                      Task.CurrentId, semaphore.Release());
                });
            }

            // Wait for half a second, to allow all the tasks to start and block.
            Thread.Sleep(500);

            // Restore the semaphore count to its maximum value.
            Console.WriteLine("Main thread calls Release(3) --> ");
            semaphore.Release(3);
            Console.WriteLine("   {0} tasks can enter the semaphore.", semaphore.CurrentCount);
            // Main thread waits for the tasks to complete.
            await Task.WhenAll(tasks);

            Console.WriteLine("Main thread exits.");

            Console.ReadLine();
        }
コード例 #36
0
 public void ScpToRemote(List <string> files, string dir_path, string dir, IVsOutputWindowPane outputWindowPane)
 {
     try
     {
         lock (lock_obj)
         {
             // ThreadHelper.ThrowIfNotOnUIThread();
             var dte = Package.GetGlobalService(typeof(DTE)) as EnvDTE80.DTE2;
             dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput).Activate();
             if (files.Count == 0)
             {
                 outputWindowPane.OutputStringThreadSafe("No file can be copied");
                 return;
             }
             ConnectionInfoStore connectionInfoStore = new ConnectionInfoStore();
             connectionInfoStore.Load();
             if (connectionInfoStore.Connections.Count < 1)
             {
                 outputWindowPane.OutputStringThreadSafe("No connection found. Add connection in [Tools] / [Options] / [Cross Platform]");
                 return;
             }
             outputWindowPane.OutputStringThreadSafe("Connecting...\n");
             if (remoteSystem == null)
             {
                 remoteSystem = new RemoteSystem((ConnectionInfo)connectionInfoStore.Connections[0]);
                 directory    = remoteSystem.FileSystem.GetDirectory(SpecialDirectory.Home);
             }
             using (var concurrencySemaphore = new System.Threading.SemaphoreSlim(8))
             {
                 int         num    = 0;
                 int         length = files.Count;
                 List <Task> tasks  = new List <Task>();
                 foreach (string file in files)
                 {
                     concurrencySemaphore.Wait();
                     var t = Task.Run(() =>
                     {
                         string str2           = file.Substring(dir_path.Length);
                         string remoteFileName = directory.FullPath + "/projects/" + dir + str2.Replace('\\', '/');
                         string remotePath     = remoteFileName.Substring(0, remoteFileName.LastIndexOf('/'));
                         try
                         {
                             if (File.Exists(file))
                             {
                                 remoteSystem.FileSystem.UploadFile(file, remoteFileName);
                                 outputWindowPane.OutputStringThreadSafe("[" + Interlocked.Increment(ref num) + "/" + length + "] " + remoteFileName + "\n");
                             }
                             else
                             {
                                 Interlocked.Increment(ref num);
                                 outputWindowPane.OutputStringThreadSafe("Skip " + file + " (file not exists)\n");
                             }
                         }
                         catch (liblinux.IO.IOException ex1)
                         {
                             if (ex1.Message.Contains("No such file"))
                             {
                                 remoteSystem.FileSystem.CreateDirectories(remotePath);
                                 remoteSystem.FileSystem.UploadFile(file, remoteFileName);
                                 outputWindowPane.OutputStringThreadSafe("[" + Interlocked.Increment(ref num) + "/" + length + "] " + remoteFileName + "\n");
                             }
                             else
                             {
                                 Interlocked.Increment(ref num);
                                 outputWindowPane.OutputStringThreadSafe("Upload failed: " + file + "\n");
                             }
                         }
                         catch (Exception ex)
                         {
                             Interlocked.Increment(ref num);
                             outputWindowPane.OutputStringThreadSafe("Upload failed: " + file + ", ex: " + ex.ToString() + "\n");
                         }
                         finally
                         {
                             concurrencySemaphore.Release();
                         }
                     });
                     tasks.Add(t);
                 }
                 Task.WaitAll(tasks.ToArray());
             }
             remoteSystem.Disconnect();
             remoteSystem.Dispose();
             outputWindowPane.OutputStringThreadSafe("Copy to " + remoteSystem.ConnectionInfo.HostNameOrAddress + " done.\n");
             // prepare for next time
             remoteSystem = new RemoteSystem((ConnectionInfo)connectionInfoStore.Connections[0]);
             directory    = remoteSystem.FileSystem.GetDirectory(SpecialDirectory.Home);
         }
     }
     catch (Exception ex)
     {
         remoteSystem = null;
         throw ex;
     }
 }
コード例 #37
0
        /// <summary>
        /// Creates grouping subscriptions and waits for the notification events to flow
        /// </summary>
        /// <param name="impersonationId"></param>
        /// <returns></returns>
        async public System.Threading.Tasks.Task CreateStreamingSubscriptionGroupingAsync(string impersonationId)
        {
            var database = EWSConstants.Config.Database;

            using (EWSDbContext context = new EWSDbContext(database))
            {
                var smtpAddresses = await context.RoomListRoomEntities.ToListAsync();

                foreach (var sMailbox in smtpAddresses)
                {
                    var addedBox = _mailboxes.AddMailbox(sMailbox.SmtpAddress);
                    if (!addedBox)
                    {
                        _traceListener.Trace("SyncProgram", $"Failed to add SMTP {sMailbox.SmtpAddress}");
                    }

                    MailboxInfo mailboxInfo = _mailboxes.Mailbox(sMailbox.SmtpAddress);
                    if (mailboxInfo != null)
                    {
                        GroupInfo groupInfo = null;
                        if (_groups.ContainsKey(mailboxInfo.GroupName))
                        {
                            groupInfo = _groups[mailboxInfo.GroupName];
                        }
                        else
                        {
                            groupInfo = new GroupInfo(mailboxInfo.GroupName, mailboxInfo.SMTPAddress, mailboxInfo.EwsUrl, EwsToken, _traceListener);
                            _groups.Add(mailboxInfo.GroupName, groupInfo);
                        }

                        if (groupInfo.Mailboxes.Count > 199)
                        {
                            // We already have enough mailboxes in this group, so we rename it and create a new one
                            // Renaming it means that we can still put new mailboxes into the correct group based on GroupingInformation
                            int i = 1;
                            while (_groups.ContainsKey($"{groupInfo.Name}-{i}"))
                            {
                                i++;
                            }

                            // Remove previous grouping name from stack
                            _groups.Remove(groupInfo.Name);

                            // Add the grouping back with the new grouping name [keep the GroupInfo with previous name]
                            _groups.Add($"{groupInfo.Name}-{i}", groupInfo);

                            // Provision a new GroupInfo with the GroupName
                            groupInfo = new GroupInfo(mailboxInfo.GroupName, mailboxInfo.SMTPAddress, mailboxInfo.EwsUrl, EwsToken, _traceListener);

                            // Add GroupInfo to stack
                            _groups.Add(mailboxInfo.GroupName, groupInfo);
                        }

                        // Add the mailbox to the collection
                        groupInfo.Mailboxes.Add(sMailbox.SmtpAddress);
                    }
                }

                // Enable the Grouping
                foreach (var _group in _groups)
                {
                    _traceListener.Trace("SyncProgram", $"Opening connections for {_group.Key}");

                    var groupName = _group.Key;
                    var groupInfo = _group.Value;

                    // Create a streaming connection to the service object, over which events are returned to the client.
                    // Keep the streaming connection open for 30 minutes.
                    if (AddGroupSubscriptions(context, groupName))
                    {
                        _traceListener.Trace("SyncProgram", $"{groupInfo.Mailboxes.Count()} mailboxes primed for StreamingSubscriptions.");
                    }
                    else
                    {
                        _traceListener.Trace("SyncProgram", $"Group {groupInfo.Name} failed in StreamingSubscription events.");
                    }
                }
            }

            using (var semaphore = new System.Threading.SemaphoreSlim(1))
            {
                // Block the Thread
                semaphore.Wait();

                // Establish the StreamingSubscriptionConnections based on the GroupingInfo
                foreach (var connection in _connections)
                {
                    var _group      = _groups[connection.Key];
                    var _connection = connection.Value;
                    if (_connection.IsOpen)
                    {
                        _group.IsConnectionOpen = true;
                        return;
                    }

                    try
                    {
                        _connection.Open();
                        _group.IsConnectionOpen = true;
                    }
                    catch (Exception ex)
                    {
                        _traceListener.Trace("SyncProgram", $"Error opening streamingsubscriptionconnection for group {_group.Name} MSG {ex.Message}");
                    }
                }

                // Lock the Thread Until its cancelled or fails
                await semaphore.WaitAsync(CancellationTokenSource.Token);
            }
        }
コード例 #38
0
 public static void Sleep(int milliseconds)
 {
     _unavailable.Wait(milliseconds);
 }
コード例 #39
0
ファイル: AllTests.cs プロジェクト: rtxlab/ice
        public static void RunWithController(TestHelper helper, IControllerPrx controller)
        {
            Communicator?communicator = helper.Communicator;

            TestHelper.Assert(communicator != null);

            var timeout = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), communicator);

            System.IO.TextWriter output = helper.Output;
            output.Write("testing connect timeout... ");
            output.Flush();
            {
                Dictionary <string, string>?properties = communicator.GetProperties();
                properties["Ice.ConnectTimeout"] = "100ms";
                using var comm = new Communicator(properties);

                var to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm);

                // Expect ConnectTimeoutException.
                controller.HoldAdapter(-1);
                try
                {
                    to.Op();
                    TestHelper.Assert(false);
                }
                catch (ConnectTimeoutException)
                {
                    // Expected.
                }
                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            {
                // Expect success.
                controller.HoldAdapter(100);
                timeout.Op();
            }
            output.WriteLine("ok");

            // The sequence needs to be large enough to fill the write/recv buffers
            byte[] seq = new byte[2000000];

            output.Write("testing connection timeout... ");
            output.Flush();
            {
                // Expect TimeoutException.
                controller.HoldAdapter(-1);
                timeout.GetConnection() !.Acm = new Acm(TimeSpan.FromMilliseconds(50),
                                                        AcmClose.OnInvocationAndIdle,
                                                        AcmHeartbeat.Off);
                try
                {
                    timeout.SendData(seq);
                    TestHelper.Assert(false);
                }
                catch (ConnectionTimeoutException)
                {
                    // Expected.
                }
                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            {
                // Expect success.
                controller.HoldAdapter(100);
                try
                {
                    timeout.SendData(new byte[1000000]);
                }
                catch (ConnectionTimeoutException)
                {
                    TestHelper.Assert(false);
                }
            }
            output.WriteLine("ok");

            output.Write("testing invocation timeout... ");
            output.Flush();
            {
                timeout.IcePing(); // Makes sure a working connection is associated with the proxy
                Connection?connection = timeout.GetConnection();
                try
                {
                    using var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
                    timeout.SleepAsync(1000, cancel: timeoutTokenSource.Token).Wait();
                    TestHelper.Assert(false);
                }
                catch (AggregateException ex) when(ex.InnerException is OperationCanceledException)
                {
                }
                timeout.IcePing();

                TestHelper.Assert(connection == timeout.GetConnection());
                try
                {
                    using var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(1000));
                    timeout.SleepAsync(100, cancel: timeoutTokenSource.Token).Wait();
                }
                catch (AggregateException ex) when(ex.InnerException is OperationCanceledException)
                {
                    TestHelper.Assert(false);
                }
                TestHelper.Assert(connection == timeout.GetConnection());
            }
            output.WriteLine("ok");

            output.Write("testing close timeout... ");
            output.Flush();
            {
                Dictionary <string, string> properties = communicator.GetProperties();
                properties["Ice.CloseTimeout"] = "100ms";
                using var comm = new Communicator(properties);

                var to = ITimeoutPrx.Parse(helper.GetTestProxy("timeout", 0), comm);

                Connection?connection  = to.GetConnection();
                Connection?connection2 = timeout.GetConnection();  // No close timeout

                TestHelper.Assert(connection != null && connection2 != null);

                controller.HoldAdapter(-1);

                // Make sure there's no ReadAsync pending
                _ = to.IcePingAsync();
                _ = timeout.IcePingAsync();

                var semaphore = new System.Threading.SemaphoreSlim(0);
                connection.Closed += (sender, args) => semaphore.Release();
                connection.Close(ConnectionClose.Gracefully);
                TestHelper.Assert(semaphore.Wait(500));

                connection2.Closed += (sender, args) => semaphore.Release();
                connection2.Close(ConnectionClose.Gracefully);
                TestHelper.Assert(!semaphore.Wait(500));

                controller.ResumeAdapter();
                timeout.Op(); // Ensure adapter is active.
            }
            output.WriteLine("ok");

            output.Write("testing invocation timeouts with collocated calls... ");
            output.Flush();
            {
                communicator.SetProperty("TimeoutCollocated.AdapterId", "timeoutAdapter");

                ObjectAdapter adapter = communicator.CreateObjectAdapter("TimeoutCollocated");
                adapter.Activate();

                ITimeoutPrx proxy = adapter.AddWithUUID(new Timeout(), ITimeoutPrx.Factory);
                try
                {
                    using var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
                    proxy.SleepAsync(500, cancel: timeoutTokenSource.Token).Wait();
                    TestHelper.Assert(false);
                }
                catch (AggregateException ex) when(ex.InnerException is OperationCanceledException)
                {
                }

                adapter.Dispose();
            }
            output.WriteLine("ok");

            controller.Shutdown();
        }
コード例 #40
0
 public print_foobar_alternately(int n)
 {
     this.n = n;
     slim2.Wait();
 }
 /// <summary>
 /// Tries to wait for the semaphore to enter.
 /// </summary>
 /// <param name="this">This <see cref="SemaphoreSlim">SemaphoreSlim</see></param>
 /// <returns><c>true</c> on success; otherwise, <c>false</c>.</returns>
 public static bool TryWait(this SemaphoreSlim @this) => @this.Wait(-1, new CancellationToken());