本文整理汇总了C#中System.Threading.ManualResetEventSlim.Wait方法的典型用法代码示例。如果您正苦于以下问题:C# ManualResetEventSlim.Wait方法的具体用法?C# ManualResetEventSlim.Wait怎么用?C# ManualResetEventSlim.Wait使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.ManualResetEventSlim
的用法示例。
在下文中一共展示了ManualResetEventSlim.Wait方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BasicUsageTest
public void BasicUsageTest ()
{
int[] array = null;
var evt = new ManualResetEventSlim (false);
var buffer = new BatchBlock<int> (10);
var block = new ActionBlock<int[]> (i =>
{
array = i;
evt.Set ();
});
buffer.LinkTo<int[]> (block);
for (int i = 0; i < 9; i++)
Assert.IsTrue (buffer.Post (i));
Assert.IsFalse (evt.Wait (100));
Assert.IsNull (array);
Assert.IsTrue (buffer.Post (42));
Assert.IsTrue (evt.Wait (1000));
Assert.IsNotNull (array);
CollectionAssert.AreEqual (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 42 }, array);
}
示例2: TestTimerStartAutoReset
public void TestTimerStartAutoReset()
{
using (var timer = new TestTimer(1))
{
var mres = new ManualResetEventSlim();
int count = 0;
int target = 1;
timer.AutoReset = false;
timer.Elapsed += (sender, e) =>
{
if (Interlocked.Increment(ref count) == target)
{
mres.Set();
}
};
timer.Start();
mres.Wait();
Assert.False(timer.Enabled, "Auto-reset timer should not be enabled after elapsed");
Assert.Equal(1, count);
count = 0;
target = 10;
mres.Reset();
timer.AutoReset = true;
mres.Wait();
timer.Stop();
Assert.InRange(count, target, int.MaxValue);
}
}
示例3: BasicUsageTest
public void BasicUsageTest()
{
Tuple<IList<int>, IList<int>> result = null;
var evt = new ManualResetEventSlim (false);
var actionBlock = new ActionBlock<Tuple<IList<int>, IList<int>>> (r =>
{
result = r;
evt.Set ();
});
var block = new BatchedJoinBlock<int, int> (2);
block.LinkTo (actionBlock);
// both targets once
Assert.IsTrue (block.Target1.Post (1));
Assert.IsFalse(evt.Wait(100));
Assert.IsNull (result);
Assert.IsTrue (block.Target2.Post (2));
Assert.IsTrue (evt.Wait (100));
Assert.IsNotNull (result);
CollectionAssert.AreEqual (new[] { 1 }, result.Item1);
CollectionAssert.AreEqual (new[] { 2 }, result.Item2);
result = null;
evt.Reset ();
// target 1 twice
Assert.IsTrue (block.Target1.Post (3));
Assert.IsFalse(evt.Wait(100));
Assert.IsNull (result);
Assert.IsTrue (block.Target1.Post (4));
Assert.IsTrue (evt.Wait (100));
Assert.IsNotNull (result);
CollectionAssert.AreEqual (new[] { 3, 4 }, result.Item1);
CollectionAssert.IsEmpty (result.Item2);
result = null;
evt.Reset ();
// target 2 twice
Assert.IsTrue (block.Target2.Post (5));
Assert.IsFalse(evt.Wait(100));
Assert.IsNull (result);
Assert.IsTrue (block.Target2.Post (6));
Assert.IsTrue (evt.Wait (100));
Assert.IsNotNull (result);
CollectionAssert.IsEmpty (result.Item1);
CollectionAssert.AreEqual (new[] { 5, 6 }, result.Item2);
}
示例4: BasicUsageTest
public void BasicUsageTest ()
{
Tuple<int, int> tuple = null;
var evt = new ManualResetEventSlim (false);
var ablock = new ActionBlock<Tuple<int, int>> (t =>
{
tuple = t;
evt.Set ();
});
var block = new JoinBlock<int, int> ();
block.LinkTo (ablock);
block.Target1.Post (42);
evt.Wait (1000);
Assert.IsNull (tuple);
block.Target2.Post (24);
evt.Wait ();
Assert.IsNotNull (tuple);
Assert.AreEqual (42, tuple.Item1);
Assert.AreEqual (24, tuple.Item2);
}
示例5: SuccessiveTimeoutTest
public void SuccessiveTimeoutTest(HostType hostType, TransportType transportType, MessageBusType messageBusType)
{
using (var host = CreateHost(hostType, transportType))
{
// Arrange
var mre = new ManualResetEventSlim(false);
host.Initialize(keepAlive: 5, messageBusType: messageBusType);
var connection = CreateConnection(host, "/my-reconnect");
using (connection)
{
connection.Reconnected += () =>
{
mre.Set();
};
connection.Start(host.Transport).Wait();
((Client.IConnection)connection).KeepAliveData = new KeepAliveData(TimeSpan.FromMilliseconds(500));
// Assert that Reconnected is called
Assert.True(mre.Wait(TimeSpan.FromSeconds(15)));
// Assert that Reconnected is called again
mre.Reset();
Assert.True(mre.Wait(TimeSpan.FromSeconds(15)));
// Clean-up
mre.Dispose();
}
}
}
示例6: BasicUsageTest
public void BasicUsageTest ()
{
Tuple<IList<int>, IList<int>, IList<string>> result = null;
var evt = new ManualResetEventSlim (false);
var actionBlock =
new ActionBlock<Tuple<IList<int>, IList<int>, IList<string>>> (r =>
{
result = r;
evt.Set ();
});
var block = new BatchedJoinBlock<int, int, string> (3);
block.LinkTo (actionBlock);
// all targets once
Assert.IsTrue (block.Target1.Post (1));
Assert.IsTrue (block.Target2.Post (2));
Assert.IsFalse (evt.Wait (100));
Assert.IsNull (result);
Assert.IsTrue (block.Target3.Post ("foo"));
Assert.IsTrue (evt.Wait (1000));
Assert.IsNotNull (result);
CollectionAssert.AreEqual (new[] { 1 }, result.Item1);
CollectionAssert.AreEqual (new[] { 2 }, result.Item2);
CollectionAssert.AreEqual (new[] { "foo" }, result.Item3);
}
示例7: PushTryPop
public void PushTryPop(int producerThreads, int consumerThreads)
{
var stack = new ConcurrentStack<int>();
var startEvent = new ManualResetEventSlim(false);
var finished = 0;
var stop = false;
var producerTasks = Enumerable.Range(0, producerThreads).Select(i => Task.Factory.StartNew(() =>
{
var count = iterations/producerThreads;
startEvent.Wait();
for (var j = 0; j < count; j++)
stack.Push(0);
Interlocked.Increment(ref finished);
if (finished >= producerThreads) stop = true;
}, TaskCreationOptions.LongRunning)).ToArray();
var consumerTasks = Enumerable.Range(0, consumerThreads).Select(i => Task.Factory.StartNew(() =>
{
int num;
startEvent.Wait();
while (!stop) stack.TryPop(out num);
}, TaskCreationOptions.LongRunning)).ToArray();
var stopwatch = Stopwatch.StartNew();
startEvent.Set();
stop = true;
Task.WaitAll(producerTasks);
Task.WaitAll(consumerTasks);
stopwatch.StopAndLog(iterations);
}
示例8: Execute
public void Execute()
{
//
// 通常の使い方.
//
var mres = new ManualResetEventSlim(false);
ThreadPool.QueueUserWorkItem(DoProc, mres);
Output.Write("メインスレッド待機中・・・");
mres.Wait();
Output.WriteLine("終了");
//
// WaitメソッドにCancellationTokenを受け付けるオーバーロードを使用。
//
mres.Reset();
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
Task.Factory.StartNew(DoProc, mres);
//
// キャンセル状態に設定.
//
tokenSource.Cancel();
Output.Write("メインスレッド待機中・・・");
try
{
//
// CancellationTokenを指定して、Wait呼び出し。
// この場合は、以下のどちらかの条件を満たした時点でWaitが解除される。
// ・別の場所にて、Setが呼ばれてシグナル状態となる。
// ・CancellationTokenがキャンセルされる。
//
// トークンがキャンセルされた場合、OperationCanceledExceptionが発生するので
// CancellationTokenを指定するWaitを呼び出す場合は、try-catchが必須となる。
//
// 今回の例の場合は、予めCancellationTokenをキャンセルしているので
// タスク処理でシグナル状態に設定されるよりも先に、キャンセル状態に設定される。
// なので、実行結果には、「*** シグナル状態に設定 ***」という文言は出力されない。
//
mres.Wait(token);
}
catch (OperationCanceledException cancelEx)
{
Output.Write("*** {0} *** ", cancelEx.Message);
}
Output.WriteLine("終了");
}
示例9: ETradeDispatcher
public ETradeDispatcher(Action<Exception> errorHandler)
: base(errorHandler)
{
const int num = 2; //num of Add() calls below
var count = 0;
var done = new ManualResetEventSlim(false);
Action report = delegate
{
if (Interlocked.Increment(ref count) == num)
done.Set();
};
int idmain, iddom;
idmain = iddom = 0;
Add(() =>
{
idmain = Thread.CurrentThread.ManagedThreadId;
report();
}, _eventThreadRequestName);
Add(() =>
{
iddom = Thread.CurrentThread.ManagedThreadId;
report();
}, _eventThreadResponseName);
done.Wait();
_eventThreadRequestId = idmain;
_eventThreadResponseId = iddom;
}
示例10: OpenCalledOnConnectionRestored
public void OpenCalledOnConnectionRestored()
{
int openInvoked = 0;
var wh = new ManualResetEventSlim();
var redisConnection = GetMockRedisConnection();
var redisMessageBus = new Mock<RedisMessageBus>(GetDependencyResolver(), new RedisScaleoutConfiguration(String.Empty, String.Empty),
redisConnection.Object) { CallBase = true };
redisMessageBus.Setup(m => m.OpenStream(It.IsAny<int>())).Callback(() =>
{
// Open would be called twice - once when connection starts and once when it is restored
if (++openInvoked == 2)
{
wh.Set();
}
});
// Creating an instance to invoke the constructor which starts the connection
var instance = redisMessageBus.Object;
redisConnection.Raise(mock => mock.ConnectionRestored += null, new Exception());
Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
}
示例11: MarkActiveStopsConnectionIfCalledAfterExtendedPeriod
public void MarkActiveStopsConnectionIfCalledAfterExtendedPeriod(HostType hostType, TransportType transportType, MessageBusType messageBusType)
{
using (var host = CreateHost(hostType, transportType))
{
host.Initialize(messageBusType: messageBusType);
var connection = CreateHubConnection(host);
using (connection)
{
var disconnectWh = new ManualResetEventSlim();
connection.Closed += () =>
{
disconnectWh.Set();
};
connection.Start(host.Transport).Wait();
// The MarkActive interval should check the reconnect window. Since this is short it should force the connection to disconnect.
((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(1);
Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired");
}
}
}
示例12: CanInvokeMethodsAndReceiveMessagesFromValidTypedHub
public async Task CanInvokeMethodsAndReceiveMessagesFromValidTypedHub(HostType hostType, TransportType transportType, MessageBusType messageBusType)
{
using (var host = CreateHost(hostType, transportType))
{
host.Initialize(messageBusType: messageBusType);
using (var connection = CreateHubConnection(host))
{
var hub = connection.CreateHubProxy("ValidTypedHub");
var echoTcs = new TaskCompletionSource<string>();
var pingWh = new ManualResetEventSlim();
hub.On<string>("Echo", message => echoTcs.TrySetResult(message));
hub.On("Ping", pingWh.Set);
await connection.Start(host.TransportFactory());
hub.InvokeWithTimeout("Echo", "arbitrary message");
Assert.True(echoTcs.Task.Wait(TimeSpan.FromSeconds(10)));
Assert.Equal("arbitrary message", echoTcs.Task.Result);
hub.InvokeWithTimeout("Ping");
Assert.True(pingWh.Wait(TimeSpan.FromSeconds(10)));
}
}
}
示例13: ConnectRetriesOnError
public async void ConnectRetriesOnError()
{
int invokationCount = 0;
var wh = new ManualResetEventSlim();
var redisConnection = GetMockRedisConnection();
var tcs = new TaskCompletionSource<object>();
tcs.TrySetCanceled();
redisConnection.Setup(m => m.ConnectAsync(It.IsAny<string>(), It.IsAny<TraceSource>())).Returns<string, TraceSource>((connectionString, trace) =>
{
if (++invokationCount == 2)
{
wh.Set();
return Task.FromResult(0);
}
else
{
return tcs.Task;
}
});
var redisMessageBus = new RedisMessageBus(GetDependencyResolver(), new RedisScaleoutConfiguration(String.Empty, String.Empty),
redisConnection.Object, false);
await redisMessageBus.ConnectWithRetry();
Assert.True(wh.Wait(TimeSpan.FromSeconds(5)));
Assert.Equal(RedisMessageBus.State.Connected, redisMessageBus.ConnectionState);
}
示例14: UseSqlNotificationsIfAvailable
public void UseSqlNotificationsIfAvailable(bool supportSqlNotifications)
{
// Arrange
var sqlDependencyAdded = false;
var retryLoopCount = 0;
var mre = new ManualResetEventSlim();
var dbProviderFactory = new MockDbProviderFactory();
var dbBehavior = new Mock<IDbBehavior>();
dbBehavior.Setup(db => db.UpdateLoopRetryDelays).Returns(_defaultRetryDelays);
dbBehavior.Setup(db => db.StartSqlDependencyListener()).Returns(supportSqlNotifications);
dbBehavior.Setup(db => db.AddSqlDependency(It.IsAny<IDbCommand>(), It.IsAny<Action<SqlNotificationEventArgs>>()))
.Callback(() =>
{
sqlDependencyAdded = true;
mre.Set();
});
var operation = new ObservableDbOperation("test", "test", new TraceSource("test"), dbProviderFactory, dbBehavior.Object);
operation.Faulted += _ => mre.Set();
operation.Queried += () =>
{
retryLoopCount++;
if (retryLoopCount > 1)
{
mre.Set();
}
};
// Act
ThreadPool.QueueUserWorkItem(_ => operation.ExecuteReaderWithUpdates((record, o) => { }));
mre.Wait();
operation.Dispose();
// Assert
Assert.Equal(supportSqlNotifications, sqlDependencyAdded);
}
示例15: Ctor_ThrowsAnException_IfLockCanNotBeGranted
public void Ctor_ThrowsAnException_IfLockCanNotBeGranted()
{
var releaseLock = new ManualResetEventSlim(false);
var lockAcquired = new ManualResetEventSlim(false);
var thread = new Thread(
() => UseConnection(connection1 =>
{
var storage = CreateStorage(connection1);
using (new SqlServerDistributedLock(storage, "exclusive", _timeout))
{
lockAcquired.Set();
releaseLock.Wait();
}
}));
thread.Start();
lockAcquired.Wait();
UseConnection(connection2 =>
{
var storage = CreateStorage(connection2);
Assert.Throws<DistributedLockTimeoutException>(
() =>
{
using (new SqlServerDistributedLock(storage, "exclusive", _timeout))
{
}
});
});
releaseLock.Set();
thread.Join();
}