本文整理汇总了C#中System.Threading.Barrier类的典型用法代码示例。如果您正苦于以下问题:C# Barrier类的具体用法?C# Barrier怎么用?C# Barrier使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Barrier类属于System.Threading命名空间,在下文中一共展示了Barrier类的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();
}
示例2: Main
public void Main()
{
barrier = new Barrier(3);
new Thread(Speak).Start("A");
new Thread(Speak).Start("B");
new Thread(Speak).Start("C");
}
示例3: RoutePeerMessages
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);
}
}
示例4: Main
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);
}
示例5: 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));
}
}
示例6: RunContext
public RunContext( RunContextParam parameters )
{
GrandOutput = CreateGrandOutputWithFakeHandler( parameters.HandlerExtraLoad, parameters.UseLocalTestStrategy, parameters.DispatcherMaxCapacity );
LoopCount = parameters.LoopCount;
Barrier = new Barrier( parameters.PoolThreadCount + parameters.NewThreadCount + 1 );
_newThreadCount = parameters.NewThreadCount;
}
示例7: TwoInstanceDependentMethodsInvoked_Exception
public void TwoInstanceDependentMethodsInvoked_Exception()
{
SingleThreadedMethodsObject o1 = new SingleThreadedMethodsObject();
Barrier barrier = new Barrier(2);
TestHelpers.InvokeSimultaneouslyAndWait(() => o1.InstanceDependentMethod(barrier), () => o1.InstanceDependentMethod2(barrier));
}
示例8: 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);
}
}
示例9: 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);
}
示例10: 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);
}
}
示例11: 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);
}
}
}
示例12: ParticleThreadManager
public ParticleThreadManager()
{
particleThread = new Thread(new ThreadStart(Run));
running = true;
barrier = new Barrier(2);
debugStrings = new List<List<string>>();
}
示例13: Barrier
public async Task When_simultaneous_reservations_are_placed_for_one_of_a_fixed_quantity_of_a_resource_then_different_values_are_reserved()
{
//arrange
var barrier = new Barrier(2);
var reservationService = new SqlReservationService(() => new ReservationServiceDbContextThatForcesConcurrencyDuringSave(barrier));
// given a fixed quantity of some resource, e.g. promo codes:
var promoCode = "promo-code-" + Any.Word();
var reservedValue1 = "firstValue:" + Any.CamelCaseName();
var reservedValue2 = "SecondValue:" + Any.CamelCaseName();
await reservationService.Reserve(reservedValue1, promoCode, Any.CamelCaseName(), TimeSpan.FromDays(-1));
await reservationService.Reserve(reservedValue2, promoCode, Any.CamelCaseName(), TimeSpan.FromDays(-1));
//act
var result = await reservationService.ReserveAny(
scope: promoCode,
ownerToken: Any.FullName(),
lease: TimeSpan.FromMinutes(2),
confirmationToken: Any.CamelCaseName());
var result2 = await reservationService.ReserveAny(
scope: promoCode,
ownerToken: Any.FullName(),
lease: TimeSpan.FromMinutes(2),
confirmationToken: Any.CamelCaseName());
//assert
result.Should().NotBe(result2);
}
示例14: RegisterActors
private void RegisterActors(CancellationToken token, Barrier gateway)
{
try
{
using (var socket = CreateOneWaySocket())
{
var localSocketIdentity = localSocketIdentityPromise.Task.Result;
gateway.SignalAndWait(token);
foreach (var actor in actorRegistrationsQueue.GetConsumingEnumerable(token))
{
try
{
var registrations = actorHandlerMap.Add(actor);
SendActorRegistrationMessage(socket, localSocketIdentity, registrations);
}
catch (Exception err)
{
logger.Error(err);
}
}
}
}
finally
{
actorRegistrationsQueue.Dispose();
}
}
示例15: 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();
}