当前位置: 首页>>代码示例>>C#>>正文


C# Barrier.SignalAndWait方法代码示例

本文整理汇总了C#中System.Threading.Barrier.SignalAndWait方法的典型用法代码示例。如果您正苦于以下问题:C# Barrier.SignalAndWait方法的具体用法?C# Barrier.SignalAndWait怎么用?C# Barrier.SignalAndWait使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Threading.Barrier的用法示例。


在下文中一共展示了Barrier.SignalAndWait方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DownloadAllTreatmentImages

        /// <summary>
        /// Download all the images for the current session
        /// </summary>
        public void DownloadAllTreatmentImages()
        {
            Barrier barrier = new Barrier(_patient.PatientTreatment.TrainingList.Count + 2);

            Task treatmentThread = new Task(() =>
            {
                //Downloading all thumbs in treatment
                DownloadTreatment();

                barrier.SignalAndWait();
            });
            treatmentThread.Start();

            foreach(Training t in _patient.PatientTreatment.TrainingList)
            {
                Task tt = new Task(() =>
                {
                    DownloadTraining(_patient.PatientTreatment.TrainingList.IndexOf(t));
                    barrier.SignalAndWait();
                });
                tt.Start();

            }

            barrier.SignalAndWait();
            barrier.Dispose();
        }
开发者ID:amirben,项目名称:VideoTherapy,代码行数:30,代码来源:DownloadCache.cs

示例2: DegreeOfParallelism_Barrier

 public static void DegreeOfParallelism_Barrier(Labeled<ParallelQuery<int>> labeled, int count, int degree)
 {
     using (ThreadPoolHelpers.EnsureMinThreadsAtLeast(degree))
     {
         var barrier = new Barrier(degree);
         Assert.Equal(Functions.SumRange(0, count), labeled.Item.WithDegreeOfParallelism(degree).Sum(x => { barrier.SignalAndWait(); return x; }));
     }
 }
开发者ID:ESgarbi,项目名称:corefx,代码行数:8,代码来源:DegreeOfParallelismTests.cs

示例3: SimpleLock_WhenDeadlocked_Throws

        public void SimpleLock_WhenDeadlocked_Throws()
        {
            object lock1 = new object();
            object lock2 = new object();
            Barrier barrier = new Barrier(2);
            Action t1 = () =>
                            {
                                lock (lock1)
                                {
                                    barrier.SignalAndWait();
                                    lock (lock2)
                                    {
                                        Thread.Sleep(100);
                                    }
                                }
                            };

            Action t2 = () =>
                            {
                                lock (lock2)
                                {
                                    barrier.SignalAndWait();
                                    lock (lock1)
                                    {
                                        Thread.Sleep(100);
                                    }
                                }
                            };

            TestHelpers.InvokeSimultaneouslyAndWaitForDeadlockDetection(t1, t2);
        }
开发者ID:olachan,项目名称:PostSharp-Toolkits,代码行数:31,代码来源:DetectDeadlocksTests.cs

示例4: ExecuteTasksSequentiallyAndInOrder

		public async Task ExecuteTasksSequentiallyAndInOrder()
		{
			using (var testSubject = new MissionControl())
			{
				var fool = testSubject.SpawnFool();
				var sentMessage = new SimpleTestMessage();
				SimpleTestMessage receivedMessage = null;
				var barrier = new Barrier(2);
				var first = fool.DoWork(
					sentMessage,
					msg =>
					{
						barrier.SignalAndWait();
						receivedMessage = msg;
					});
				var second = fool.DoWork(sentMessage, msg => { barrier.SignalAndWait(); });
				var done = Task.WhenAll(first, second)
					.ContinueWith(
						t =>
						{
							barrier.Dispose();
							return Work.Completed;
						});
				var timeout = Task.Delay(100.Milliseconds())
					.ContinueWith(t => Work.TimedOut);
				var result = await await Task.WhenAny(done, timeout);
				result.Should()
					.Be(Work.TimedOut);
			}
		}
开发者ID:arlobelshee,项目名称:Fools.net,代码行数:30,代码来源:FoolExecutionAndMessaging.cs

示例5: Test_ClearDeadThreads

 public void Test_ClearDeadThreads()
 {
     //---------------Set up test pack-------------------
     const int BarrierTimeout = 10000;
     var dataAccessorMain = new DataAccessorInMemory();
     var dataAccessor = new DataAccessorThreadSplitter(dataAccessorMain);
     var expectedDataAccessorForThread = new DataAccessorInMemory();
     using (var entryBarrier = new Barrier(2))
     using (var exitBarrier = new Barrier(2))
     {
         var thread = new Thread(() =>
         {
             dataAccessor.AddDataAccessorForThread(expectedDataAccessorForThread);
             entryBarrier.SignalAndWait(BarrierTimeout);
             exitBarrier.SignalAndWait(BarrierTimeout);
         });
         thread.Start();
         entryBarrier.SignalAndWait(BarrierTimeout);
         //---------------Assert preconditions---------------
         Assert.AreSame(expectedDataAccessorForThread, dataAccessor.GetDataAccessorForThread(thread));
         //---------------Execute Test ----------------------
         exitBarrier.SignalAndWait(BarrierTimeout);
         thread.Join();
         dataAccessor.ClearDeadThreads();
         //---------------Test Result -----------------------
         var exception = Assert.Throws<HabaneroDeveloperException>(() => dataAccessor.GetDataAccessorForThread(thread));
         StringAssert.Contains("Data accessor for thread does not exist", exception.Message);
     }
 }
开发者ID:Chillisoft,项目名称:habanero,代码行数:29,代码来源:TestDataAccessorThreadSplitter.cs

示例6: Test_WithThread

 public void Test_WithThread()
 {
     //---------------Set up test pack-------------------
     const int BarrierTimeout = 10000;
     var dataAccessorMain = new DataAccessorInMemory();
     var dataAccessor = new DataAccessorThreadSplitter(dataAccessorMain);
     var expectedDataAccessorForThread = new DataAccessorInMemory();
     using (var entryBarrier = new Barrier(2))
     using (var exitBarrier = new Barrier(2))
     {
         var thread = new Thread(() =>
         {
             dataAccessor.AddDataAccessorForThread(expectedDataAccessorForThread);
             entryBarrier.SignalAndWait(BarrierTimeout);
             exitBarrier.SignalAndWait(BarrierTimeout);
         });
         thread.Start();
         entryBarrier.SignalAndWait(BarrierTimeout);
         //---------------Execute Test ----------------------
         var dataAccessorForThread = dataAccessor.GetDataAccessorForThread(thread);
         exitBarrier.SignalAndWait(BarrierTimeout);
         //---------------Test Result -----------------------
         Assert.AreSame(expectedDataAccessorForThread, dataAccessorForThread);
     }
 }
开发者ID:Chillisoft,项目名称:habanero,代码行数:25,代码来源:TestDataAccessorThreadSplitter.cs

示例7: CreateFor_GivenActionAndNoInterval_ShouldRunActionOnceInASecond

        public void CreateFor_GivenActionAndNoInterval_ShouldRunActionOnceInASecond()
        {
            //---------------Set up test pack-------------------
            var sut = Create();
            var barrier1 = new Barrier(2);
            var barrier2 = new Barrier(2);
            var runs = 0;
            //---------------Assert Precondition----------------
            //---------------Execute Test ----------------------
            sut.CreateFor(() =>
            {
                if (runs == 0)
                    barrier1.SignalAndWait();
                if (++runs == 2)
                    barrier2.SignalAndWait();

            });
            barrier1.SignalAndWait();
            Thread.Sleep(1000);
            var start = DateTime.Now;
            barrier2.SignalAndWait();
            var end = DateTime.Now;
            //---------------Test Result -----------------------
            Assert.That(end - start, Is.LessThanOrEqualTo(TimeSpan.FromMilliseconds(500)));
        }
开发者ID:Chillisoft,项目名称:splunk4net,代码行数:25,代码来源:TestTimerFactory.cs

示例8: CalculatePrimesParallel

        private static int[] CalculatePrimesParallel(int range)
        {
            var results = new List<int>();
            var b = new Barrier(Environment.ProcessorCount + 1);
            for(var core=0; core < Environment.ProcessorCount; ++core)
            {
                var coreX = core;
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    var threadResults = new List<int>();
                    for (var number = 3 + coreX; number < range; number += Environment.ProcessorCount)
                    {
                        var foundPrime = true;
                        for (var divisor = 2; divisor * divisor <= number; divisor++)
                            if (number % divisor == 0)
                                foundPrime = false;

                        if (foundPrime)
                        {
                            results.Add(number);
                        }
                    }
                    b.SignalAndWait();
                });
            }

            b.SignalAndWait();
            return results.ToArray();
        }
开发者ID:Laubeee,项目名称:ecnf,代码行数:29,代码来源:Program.cs

示例9: Construct_GivenSemaphoreSlim_ShouldLockIt

        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);
                }
            }
        }
开发者ID:Chillisoft,项目名称:splunk4net,代码行数:27,代码来源:TestLenientAutoLocker.cs

示例10: TestEtw

        public void TestEtw()
        {
            using (var listener = new TestEventListener("System.Threading.Tasks.Parallel.EventSource", EventLevel.Verbose))
            {
                var events = new ConcurrentQueue<int>();
                listener.RunWithCallback(ev => events.Enqueue(ev.EventId), () => {
                    Parallel.For(0, 10000, i => { });

                    var barrier = new Barrier(2);
                    Parallel.Invoke(
                        () => barrier.SignalAndWait(),
                        () => barrier.SignalAndWait());
                });

                const int BeginLoopEventId = 1;
                const int BeginInvokeEventId = 3;
                Assert.Equal(expected: 1, actual: events.Count(i => i == BeginLoopEventId));
                Assert.Equal(expected: 1, actual: events.Count(i => i == BeginInvokeEventId));

                const int EndLoopEventId = 2;
                const int EndInvokeEventId = 4;
                Assert.Equal(expected: 1, actual: events.Count(i => i == EndLoopEventId));
                Assert.Equal(expected: 1, actual: events.Count(i => i == EndInvokeEventId));

                const int ForkEventId = 5;
                const int JoinEventId = 6;
                Assert.True(events.Count(i => i == ForkEventId) >= 1);
                Assert.Equal(events.Count(i => i == ForkEventId), events.Count(i => i == JoinEventId));
            }
        }
开发者ID:johnhhm,项目名称:corefx,代码行数:30,代码来源:EtwTests.cs

示例11: Main

        static void Main(string[] args)
        {
            // create a barrier
            Barrier barrier = new Barrier(2);

            // create a task that will complete
            Task.Factory.StartNew(() => {
                Console.WriteLine("Good task starting phase 0");
                barrier.SignalAndWait();
                Console.WriteLine("Good task starting phase 1");
                barrier.SignalAndWait();
                Console.WriteLine("Good task completed");
            });

            // create a task that will throw an exception
            // with a selective continuation that will reduce the
            // particpant count in the barrier
            Task.Factory.StartNew(() => {
                Console.WriteLine("Bad task 1 throwing exception");
                throw new Exception();

            }).ContinueWith(antecedent => {
                // reduce the particpant count
                Console.WriteLine("Reducing the barrier participant count");
                barrier.RemoveParticipant();
            }, TaskContinuationOptions.OnlyOnFaulted);

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }
开发者ID:clp-takekawa,项目名称:codes-from-books,代码行数:31,代码来源:Listing_13.cs

示例12: TestBackgroundWorkerBasic

        public void TestBackgroundWorkerBasic()
        {
            var orignal = SynchronizationContext.Current;
            try
            {
                SynchronizationContext.SetSynchronizationContext(null);

                const int expectedResult = 42;
                const int expectedReportCallsCount = 5;
                int actualReportCallsCount = 0;
                var worker = new BackgroundWorker() { WorkerReportsProgress = true };
                var progressBarrier = new Barrier(2, barrier => ++actualReportCallsCount);
                var workerCompletedEvent = new ManualResetEventSlim(false);

                worker.DoWork += (sender, e) =>
                {
                    for (int i = 0; i < expectedReportCallsCount; i++)
                    {
                        worker.ReportProgress(i);
                        progressBarrier.SignalAndWait();
                    }

                    e.Result = expectedResult;
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    try
                    {
                        Assert.Equal(expectedResult, (int)e.Result);
                        Assert.False(worker.IsBusy);
                    }
                    finally
                    {
                        workerCompletedEvent.Set();
                    }
                };
                worker.ProgressChanged += (sender, e) =>
                {
                    progressBarrier.SignalAndWait();
                };

                worker.RunWorkerAsync();

                // wait for singal from WhenRunWorkerCompleted
                Assert.True(workerCompletedEvent.Wait(TimeoutLong));
                Assert.False(worker.IsBusy);
                Assert.Equal(expectedReportCallsCount, actualReportCallsCount);
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(orignal);
            }
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:53,代码来源:BackgroundWorkerTests.cs

示例13: CurrentManagedThreadId_DifferentForActiveThreads

 public void CurrentManagedThreadId_DifferentForActiveThreads()
 {
     var ids = new HashSet<int>();
     Barrier b = new Barrier(10);
     Task.WaitAll((from i in Enumerable.Range(0, b.ParticipantCount)
                   select Task.Factory.StartNew(() =>
                   {
                       b.SignalAndWait();
                       lock (ids) ids.Add(Environment.CurrentManagedThreadId);
                       b.SignalAndWait();
                   }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray());
     Assert.Equal(b.ParticipantCount, ids.Count);
 }
开发者ID:dotnet,项目名称:corefx,代码行数:13,代码来源:EnvironmentTests.cs

示例14: TransactionTest_forceDistributedTransaction

        public void TransactionTest_forceDistributedTransaction()
        {
            var id = new Guid("9e15c907-68da-44a0-8197-81c0ef1d88c9");

            var barrier = new Barrier(2);

            using (GetNewServer(requestedStorage: "esent"))
            using (var documentStore = new DocumentStore() { Url = "http://localhost:8079", EnlistInDistributedTransactions = true }.Initialize())
            {
                if(documentStore.DatabaseCommands.GetStatistics().SupportsDtc == false)
                    return;

                using (var session = documentStore.OpenSession())
                {
                    session.Store(new LocationView{Id = id});

                    session.SaveChanges();
                }
                // Delete location (savechanges immediately) but rollback efter sleeping 10 seconds
                var task = new Task(() =>
                {
                    using (var tx = new TransactionScope())
                    {
                        ForceDistributedTransaction();

                        using (var session = documentStore.OpenSession())
                        {
                            session.Advanced.AllowNonAuthoritativeInformation = false;
                            var locationView = session.Load<LocationView>(id);
                            session.Delete(locationView);

                            session.SaveChanges();
                        }
                        barrier.SignalAndWait();
                        barrier.SignalAndWait();
                        // We don't complete so the deletion will rollback
                    }
                });
                task.Start();

                barrier.SignalAndWait();

                Assert.True(CanReadLocation(documentStore, id, forceDistributedTransaction: true));

                barrier.SignalAndWait();
                task.Wait();
                Assert.True(CanReadLocation(documentStore, id, forceDistributedTransaction: true));
            }
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:49,代码来源:Hendrik.cs

示例15: Main

        static void Main(string[] args) {
            var participants = 5;

            // We create a CancellationTokenSource to be able to initiate the cancellation
            var tokenSource = new CancellationTokenSource();
            // We create a barrier object to use it for the rendez-vous points
            var barrier = new Barrier(participants,
                b => {
                    Console.WriteLine("{0} paricipants are at rendez-vous point {1}.",
                                    b.ParticipantCount,
                                    b.CurrentPhaseNumber);
                });

            for (int i = 0; i < participants; i++) {
                var localCopy = i;
                Task.Delay(1000 * localCopy + 1, tokenSource.Token)
                    .ContinueWith(_ => {
                        Console.WriteLine("Task {0} left point A!", localCopy);
                        Thread.Sleep(1000 * localCopy + 1); // Do some "work"
                        if (localCopy % 2 == 0) {
                            Console.WriteLine("Task {0} arrived at point B!", localCopy);
                            barrier.SignalAndWait(tokenSource.Token);
                        }
                        else {
                            Console.WriteLine("Task {0} changed its mind and went back!", localCopy);
                            barrier.RemoveParticipant();
                            return;
                        }
                    }, TaskContinuationOptions.NotOnCanceled)
                    .ContinueWith(_ => {
                        Thread.Sleep(1000 * localCopy + 1);
                        Console.WriteLine("Task {0} arrived at point C!", localCopy);
                        barrier.SignalAndWait(tokenSource.Token);
                    }, TaskContinuationOptions.NotOnCanceled);
            }

            Console.WriteLine("Main thread is waiting for {0} tasks!", barrier.ParticipantsRemaining - 1);
            Console.WriteLine("Press enter to cancel!");
            Console.ReadLine();
            if (barrier.CurrentPhaseNumber < 2) {
                tokenSource.Cancel();
                Console.WriteLine("We canceled the operation!");
            }
            else {
                Console.WriteLine("Too late to cancel!");
            }
            Console.WriteLine("Main thread is done!");
            Console.ReadLine();
        }
开发者ID:vikramadhav,项目名称:Certification_70-483,代码行数:49,代码来源:BarrierWithTasks.cs


注:本文中的System.Threading.Barrier.SignalAndWait方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。