public SignalAndWait ( TimeSpan timeout ) : Boolean | ||
timeout | TimeSpan | A |
Результат | Boolean |
/// <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(); }
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; })); } }
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)); } }
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(); }
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); } } }
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); }
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); } }
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); } }
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); } }
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))); }
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(); }
public static void Water() { Console.WriteLine("Putting water to boil (takes a bit longer)"); Thread.Sleep(2000); barrier.SignalAndWait(); Console.WriteLine("Pouring water into cup."); barrier.SignalAndWait(); Console.WriteLine("Turn off the water heater."); }
public static void Water() { Console.WriteLine("Phase 0. Putting the kettle on (takes a bit longer)"); Thread.Sleep(2000); barrier.SignalAndWait(); Console.WriteLine("Phase 1. Pouring water into cup"); barrier.SignalAndWait(); Console.WriteLine("Phase 2. Putting the kettle away"); }
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); } }
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); }
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(); }
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)); } }
static void Main(string[] args) { const int numberTasks = 2; const int partitionSize = 1000000; var data = new List <string>(FillData(partitionSize * numberTasks)); var barrier = new System.Threading.Barrier(numberTasks + 1); var taskFactory = new TaskFactory(); var tasks = new Task <int[]> [numberTasks]; for (int i = 0; i < numberTasks; i++) { tasks[i] = taskFactory.StartNew <int[]>(CalculationInTask, Tuple.Create(i, partitionSize, barrier, data)); } barrier.SignalAndWait(); var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) => { return(c1 + c2); }); char ch = 'a'; int sum = 0; }
public void Barrier() { var range = Enumerable.Range(0, 10).ToList(); var barrier = new Barrier(range.Count + 1); Parallel.ForEach(range, i => { Task.Run(() => { Console.Write(i + " "); barrier.SignalAndWait(); Console.WriteLine($"{i} stopped"); }); }); barrier.SignalAndWait(); Console.WriteLine("done"); }
public void ObjectFromEmptyContainerConcurently() { const int Threads = 40; var barrier = new System.Threading.Barrier(Threads); var countdown = new CountdownEvent(Threads); var random = new Random(); var errors = false; for (int i = 0; i < Threads; i++) { Task.Factory.StartNew( wait => { barrier.SignalAndWait(); Task.Delay((int)wait).Wait(); try { var result = Container.Resolve <object>(); } catch { errors = true; } countdown.Signal(); }, random.Next(0, 3), TaskCreationOptions.LongRunning); } countdown.Wait(); Assert.IsFalse(errors); }
public static bool CancelAfterWait() { TestHarness.TestLog("* BarrierCancellationTests.CancelAfterWait()"); bool passed = true; CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = cancellationTokenSource.Token; const int numberParticipants = 3; Barrier barrier = new Barrier(numberParticipants); ThreadPool.QueueUserWorkItem( (args) => { Thread.Sleep(1000); cancellationTokenSource.Cancel(); } ); //Now wait.. the wait should abort and an exception should be thrown passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown( () => barrier.SignalAndWait(cancellationToken), cancellationToken, "An OCE(null) should have been thrown that references the cancellationToken."); //Test that backout occured. passed &= TestHarnessAssert.AreEqual(numberParticipants, barrier.ParticipantsRemaining, "All participants should remain as the current one should have backout out its signal"); // the token should not have any listeners. // currently we don't expose this.. but it was verified manually return passed; }
private void RoutePeerMessages(CancellationToken token, Barrier gateway) { try { using (var scaleOutFrontend = CreateScaleOutFrontendSocket()) { var localSocketIdentity = localSocketIdentityPromise.Task.Result; gateway.SignalAndWait(token); while (!token.IsCancellationRequested) { try { var message = (Message) scaleOutFrontend.ReceiveMessage(token); if (message != null) { message.SetSocketIdentity(localSocketIdentity); scaleOutFrontend.SendMessage(message); messageTracer.ReceivedFromOtherNode(message); } } catch (Exception err) { logger.Error(err); } } } } catch (Exception err) { logger.Error(err); } }
public void TestAbilityToFireImmediatelyWhenStartedBefore() { List<DateTime> jobExecTimestamps = new List<DateTime>(); Barrier barrier = new Barrier(2); IScheduler sched = CreateScheduler("testAbilityToFireImmediatelyWhenStartedBefore", 5); sched.Context.Put(Barrier, barrier); sched.Context.Put(DateStamps, jobExecTimestamps); sched.Start(); Thread.Yield(); IJobDetail job1 = JobBuilder.Create<TestJobWithSync>() .WithIdentity("job1") .Build(); ITrigger trigger1 = TriggerBuilder.Create() .ForJob(job1) .Build(); DateTime sTime = DateTime.UtcNow; sched.ScheduleJob(job1, trigger1); barrier.SignalAndWait(testTimeout); sched.Shutdown(false); DateTime fTime = jobExecTimestamps[0]; Assert.That(fTime - sTime < TimeSpan.FromMilliseconds(7000), "Immediate trigger did not fire within a reasonable amount of time."); }
public void Instance_ThreadSafe() { using (var gate = new Barrier(5)) { var result = new ConcurrentBag<AnyConstructorFinder>(); Action test = () => { gate.SignalAndWait(20); var instance = AnyConstructorFinder.Instance; Thread.MemoryBarrier(); result.Add(instance); }; var cycleState = Parallel.For(0, 200, new ParallelOptions { MaxDegreeOfParallelism = 15 }, x => { test(); }) ; while (!cycleState.IsCompleted) { Thread.Sleep(100); } Assert.IsTrue(result.All(x => x != null)); Assert.IsTrue(result.Distinct().Count() == 1); } }
static void Main() { const int numberTasks = 2; const int partitionSize = 1000000; var data = new List<string>(FillData(partitionSize * numberTasks)); var barrier = new Barrier(numberTasks + 1); var taskFactory = new TaskFactory(); var tasks = new Task<int[]>[numberTasks]; for (int i = 0; i < numberTasks; i++) { tasks[i] = taskFactory.StartNew<int[]>(CalculationInTask, Tuple.Create(i, partitionSize, barrier, data)); } barrier.SignalAndWait(); var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) => { return c1 + c2; }); char ch = 'a'; int sum = 0; foreach (var x in resultCollection) { Console.WriteLine("{0}, count: {1}", ch++, x); sum += x; } Console.WriteLine("main finished {0}", sum); Console.WriteLine("remaining {0}, phase {1}", barrier.ParticipantsRemaining, barrier.CurrentPhaseNumber); }
public void TestPoolContention() { var barrier = new Barrier(N); var tasks = new Task[N]; var totalTimesAcquired = 0; Assert.AreEqual(pool.maxThingId, 0); for (int i = 0; i < N; i++) { var t = Task.Run(() => { barrier.SignalAndWait(); // Takes time for all threads to spin up for (int j = 0; j < 128; j++) { using (var pooled = pool.GetAsync().Result) // blocks { Interlocked.Increment(ref totalTimesAcquired); } } }); tasks[i] = t; // These N tasks do not yield their thread } Task.WaitAll(tasks); Assert.AreEqual(PoolSize, pool.maxThingId); Assert.AreEqual(PoolSize, pool.CurrentFreeCount); Assert.AreEqual(PoolSize, pool.CurrentPoolSize); Assert.AreEqual(N * 128, totalTimesAcquired); }
public void EventRaisedWithActionHandler() { RunWithoutSyncCtx(() => { Barrier b = new Barrier(2); Progress<int> p = new Progress<int>(i => { Assert.Equal(b.CurrentPhaseNumber, i); b.SignalAndWait(); }); for (int i = 0; i < 3; i++) { ((IProgress<int>)p).Report(i); b.SignalAndWait(); } }); }
public void Append_GivenLoggingEvent_WhenIsFirstEvent_ShouldKickOffTaskToLogToSplunk() { //---------------Set up test pack------------------- var factory = Substitute.For<ISplunkWriterFactory>(); var taskRunner = Substitute.For<ITaskRunner>(); var db = Substitute.For<ILogBufferItemRepository>(); var dbFactory = CreateSubstituteBufferFactoryWith(db); Task<AsyncLogResult> logTask = null; var firstBarrier = new Barrier(2); var secondBarrier = new Barrier(2); taskRunner.Run(Arg.Any<Func<AsyncLogResult>>()) .ReturnsForAnyArgs(ci => { logTask = new Task<AsyncLogResult>(() => { var result = ci.Arg<Func<AsyncLogResult>>()(); firstBarrier.SignalAndWait(); secondBarrier.SignalAndWait(); // don't let this exit here to prove unbuffer didn't happen return result; }); return logTask; }); var sut = Create(taskRunner, factory, dbFactory); sut.Name = RandomValueGen.GetRandomString(1, 10); var logEvent = CreateRandomLoggingEvent(); var writer = Substitute.For<ISplunkWriter>(); factory.CreateFor(sut.Name).ReturnsForAnyArgs(ci => writer); writer.Log(Arg.Any<string>()) .ReturnsForAnyArgs(ci => ImmediateTaskRunnerBuilder.CreateImmediateTaskFor(() => true)); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- sut.DoAppend(logEvent); //---------------Test Result ----------------------- // not called just yet... factory.Received().CreateFor(sut.Name); writer.DidNotReceive().Log(Arg.Any<string>()); logTask.Start(); firstBarrier.SignalAndWait(); writer.Received().Log(JsonConvert.SerializeObject(logEvent, Formatting.None, new JsonConverterWhichProducesHierachicalOutputOnLog4NetMessageObjects())); db.DidNotReceive().Unbuffer(Arg.Any<long>()); }
public void MultpleTimers_PeriodicTimerIsntBlockedByBlockedCallback() { int callbacks = 2; Barrier b = new Barrier(callbacks + 1); Timer t = null; t = new Timer(_ => { if (Interlocked.Decrement(ref callbacks) >= 0) { Assert.True(b.SignalAndWait(MaxPositiveTimeoutInMs)); } t.Dispose(); }, null, -1, -1); t.Change(1, 50); Assert.True(b.SignalAndWait(MaxPositiveTimeoutInMs)); GC.KeepAlive(t); }
public void Start() { _barrier = new Barrier(2); _worker = new Thread(Worker); _worker.Start(); _barrier.SignalAndWait(); _barrier.Dispose(); _barrier = null; }
public void EventRaisedWithEventHandler() { RunWithoutSyncCtx(() => { Barrier b = new Barrier(2); Progress<int> p = new Progress<int>(); p.ProgressChanged += (s, i) => { Assert.Same(s, p); Assert.Equal(b.CurrentPhaseNumber, i); b.SignalAndWait(); }; for (int i = 0; i < 3; i++) { ((IProgress<int>)p).Report(i); b.SignalAndWait(); } }); }
public StopTheThreadPoolContext() { int numProcs = Environment.ProcessorCount; var barrier = new Barrier(numProcs + 1); ThreadPool.GetMaxThreads(out originalWorkerThreads, out originalIOThreads); ThreadPool.SetMaxThreads(numProcs, originalIOThreads); for (int i = 0; i < numProcs; i++) { ThreadPool.QueueUserWorkItem( delegate { barrier.SignalAndWait(); testComplete.Wait(); }); } barrier.SignalAndWait(); }
public void Test() { var container = Container(); var barrier = new Barrier(2); var otherThreadTask = Task.Run(delegate { barrier.SignalAndWait(); container.Get<A>(); }); var error = Assert.Throws<SimpleContainerException>(() => { barrier.SignalAndWait(); Thread.Sleep(20); container.Get<A>(); }); var isValidException = Is.EqualTo("parameter [parameter] of service [A] is not configured\r\n\r\n!A\r\n\tServiceWithDelay\r\n\t!parameter <---------------"); Assert.That(error.Message, isValidException); var otherTaskException = Assert.Throws<AggregateException>(otherThreadTask.Wait); Assert.That(otherTaskException.InnerExceptions.Single().Message, isValidException); }
static void Main() { const int numberTasks = 2; const int partitionSize = 1000000; const int loops = 5; var taskResults = new Dictionary<int, int[][]>(); var data = new List<string>[loops]; for (int i = 0; i < loops; i++) { data[i] = new List<string>(FillData(partitionSize * numberTasks)); } var barrier = new Barrier(1); LogBarrierInformation("initial participants in barrier", barrier); for (int i = 0; i < numberTasks; i++) { barrier.AddParticipant(); int jobNumber = i; taskResults.Add(i, new int[loops][]); for (int loop = 0; loop < loops; loop++) { taskResults[i][loop] = new int[26]; } WriteLine($"Main - starting task job {jobNumber}"); Task.Run(() => CalculationInTask(jobNumber, partitionSize, barrier, data, loops, taskResults[jobNumber])); } for (int loop = 0; loop < 5; loop++) { LogBarrierInformation("main task, start signaling and wait", barrier); barrier.SignalAndWait(); LogBarrierInformation("main task waiting completed", barrier); // var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) => c1 + c2); int[][] resultCollection1 = taskResults[0]; int[][] resultCollection2 = taskResults[1]; var resultCollection = resultCollection1[loop].Zip(resultCollection2[loop], (c1, c2) => c1 + c2); char ch = 'a'; int sum = 0; foreach (var x in resultCollection) { WriteLine($"{ch++}, count: {x}"); sum += x; } LogBarrierInformation($"main task finished loop {loop}, sum: {sum}", barrier); } WriteLine("at the end"); ReadLine(); }
private static void Participant1() { Console.WriteLine("Participant1 executing phase 0"); Barrier.SignalAndWait(); Console.WriteLine("Participant1 executing phase 1"); Barrier.SignalAndWait(); Console.WriteLine("Participant1 executing phase 2"); Barrier.SignalAndWait(); Console.WriteLine("Participant1 done with it's execution"); }
public void MultipleResolvesAtTheSameTimeCauseConcurrencyException() { var container = Container; container.RegisterInstance <string>("a value"); const int Threads = 40; var barrier = new System.Threading.Barrier(Threads); var countdown = new CountdownEvent(Threads); var random = new Random(); var errors = false; for (int i = 0; i < Threads; i++) { Task.Factory.StartNew( wait => { barrier.SignalAndWait(); Task.Delay((int)wait).Wait(); try { container.Resolve <ClassWithMultipleConstructorParameters>(); } catch { errors = true; } countdown.Signal(); }, random.Next(0, 3), TaskCreationOptions.LongRunning); } countdown.Wait(); Assert.IsFalse(errors); }