本文整理汇总了C#中System.Threading.CountdownEvent.Reset方法的典型用法代码示例。如果您正苦于以下问题:C# CountdownEvent.Reset方法的具体用法?C# CountdownEvent.Reset怎么用?C# CountdownEvent.Reset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.CountdownEvent
的用法示例。
在下文中一共展示了CountdownEvent.Reset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: everything_should_go_fine
public void everything_should_go_fine()
{
var miniNode = new MiniNode(PathName);
miniNode.Start();
var tcpPort = miniNode.TcpEndPoint.Port;
var tcpSecPort = miniNode.TcpSecEndPoint.Port;
var httpPort = miniNode.HttpEndPoint.Port;
const int cnt = 50;
var countdown = new CountdownEvent(cnt);
// --- first part of events
WriteEvents(cnt, miniNode, countdown);
Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(10)), "Too long writing first part of events.");
countdown.Reset();
// -- set up truncation
var truncatePosition = miniNode.Db.Config.WriterCheckpoint.ReadNonFlushed();
miniNode.Db.Config.TruncateCheckpoint.Write(truncatePosition);
miniNode.Db.Config.TruncateCheckpoint.Flush();
// --- second part of events
WriteEvents(cnt, miniNode, countdown);
Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(10)), "Too long writing second part of events.");
countdown.Reset();
miniNode.Shutdown(keepDb: true, keepPorts: true);
// --- first restart and truncation
miniNode = new MiniNode(PathName, tcpPort, tcpSecPort, httpPort);
miniNode.Start();
Assert.AreEqual(-1, miniNode.Db.Config.TruncateCheckpoint.Read());
Assert.That(miniNode.Db.Config.WriterCheckpoint.Read(), Is.GreaterThanOrEqualTo(truncatePosition));
// -- third part of events
WriteEvents(cnt, miniNode, countdown);
Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(10)), "Too long writing third part of events.");
countdown.Reset();
miniNode.Shutdown(keepDb: true, keepPorts: true);
// -- second restart
miniNode = new MiniNode(PathName, tcpPort, tcpSecPort, httpPort);
Assert.AreEqual(-1, miniNode.Db.Config.TruncateCheckpoint.Read());
miniNode.Start();
// -- if we get here -- then everything is ok
miniNode.Shutdown();
}
示例2: ExecuteLevel
protected override void ExecuteLevel(IList<Computation> computationsOfLevel)
{
using (var countEvent = new CountdownEvent(1))
{
foreach (var item in computationsOfLevel)
{
var cc = item.Context as ParallelComputationContext;
if (cc != null)
{
countEvent.AddCount();
cc.RunTransform(() =>
{
item.Transform();
countEvent.Signal();
});
}
else
{
countEvent.Signal();
countEvent.Wait();
item.Transform();
countEvent.Reset();
}
OnComputationCompleted(new ComputationEventArgs(item));
}
countEvent.Signal();
countEvent.Wait();
}
}
示例3: MultipleBindingTest
public void MultipleBindingTest ()
{
BufferBlock<int> buffer = new BufferBlock<int> ();
var evt = new CountdownEvent (10);
int count = 0;
ActionBlock<int> block = new ActionBlock<int> ((i) => { Interlocked.Decrement (ref count); evt.Signal (); });
IDisposable bridge = buffer.LinkTo (block);
for (int i = 0; i < 10; i++)
Assert.IsTrue (buffer.Post (i));
evt.Wait ();
Assert.AreEqual (-10, count);
count = 0;
evt.Reset ();
bridge.Dispose ();
ActionBlock<int> block2 = new ActionBlock<int> ((i) => { Interlocked.Increment (ref count); evt.Signal (); });
buffer.LinkTo (block2);
for (int i = 0; i < 10; i++)
Assert.IsTrue (buffer.Post (i));
evt.Wait ();
Assert.AreEqual (10, count);
}
示例4: Should_release_the_pool
public void Should_release_the_pool()
{
// Arrange
var blockTheThread = new AutoResetEvent(false);
var countdownEvent = new CountdownEvent(1);
var queue = Substitute.For<IInMemoryPriorityQueue<GenericPriorityMessage<BasicDeliverEventArgs>>>();
queue.When(x => x.Dequeue()).Do(callInfo => { countdownEvent.Signal(); blockTheThread.WaitOne(); });
var consumer = new PriorityBurrowConsumer(Substitute.For<IModel>(), Substitute.For<IMessageHandler>(), Substitute.For<IRabbitWatcher>(), false, 1);
consumer.Init(queue, Substitute.For<CompositeSubscription>(), 1, Guid.NewGuid().ToString());
consumer.Ready();
// Action
countdownEvent.Wait();
countdownEvent.Reset();
blockTheThread.Set();
consumer.MessageHandlerHandlingComplete(null);
countdownEvent.Wait();
// Assert
queue.Received(2).Dequeue();
consumer.Dispose();
blockTheThread.Dispose();
}
示例5: with_truncate_position_in_completed_chunk_everything_should_go_fine
public void with_truncate_position_in_completed_chunk_everything_should_go_fine()
{
const int chunkSize = 1024*1024;
const int cachedSize = chunkSize*3;
var miniNode = new MiniNode(PathName, chunkSize: chunkSize, cachedChunkSize: cachedSize, inMemDb: false);
miniNode.Start();
var tcpPort = miniNode.TcpEndPoint.Port;
var tcpSecPort = miniNode.TcpSecEndPoint.Port;
var httpPort = miniNode.ExtHttpEndPoint.Port;
const int cnt = 1;
var countdown = new CountdownEvent(cnt);
// --- first part of events
WriteEvents(cnt, miniNode, countdown, MiniNode.ChunkSize / 5 * 3);
Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(10)), "Took too long writing first part of events.");
countdown.Reset();
// -- set up truncation
var truncatePosition = miniNode.Db.Config.WriterCheckpoint.ReadNonFlushed();
miniNode.Db.Config.TruncateCheckpoint.Write(truncatePosition);
miniNode.Db.Config.TruncateCheckpoint.Flush();
// --- second part of events
WriteEvents(cnt, miniNode, countdown, MiniNode.ChunkSize / 2);
Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(10)), "Took too long writing second part of events.");
countdown.Reset();
miniNode.Shutdown(keepDb: true, keepPorts: true);
// --- first restart and truncation
miniNode = new MiniNode(PathName, tcpPort, tcpSecPort, httpPort, chunkSize: chunkSize, cachedChunkSize: cachedSize, inMemDb: false);
miniNode.Start();
Assert.AreEqual(-1, miniNode.Db.Config.TruncateCheckpoint.Read());
Assert.That(miniNode.Db.Config.WriterCheckpoint.Read(), Is.GreaterThanOrEqualTo(truncatePosition));
// -- third part of events
WriteEvents(cnt, miniNode, countdown, MiniNode.ChunkSize / 5);
Assert.IsTrue(countdown.Wait(TimeSpan.FromSeconds(10)), "Took too long writing third part of events.");
countdown.Reset();
// -- if we get here -- then everything is ok
miniNode.Shutdown();
}
示例6: IsSetTestCase
public void IsSetTestCase()
{
var evt = new CountdownEvent (5);
Assert.IsFalse(evt.IsSet, "#1");
evt.Signal(5);
Assert.IsTrue(evt.IsSet, "#2");
evt.Reset();
Assert.IsFalse(evt.IsSet, "#3");
}
示例7: Dispose
public void Dispose ()
{
var ce = new CountdownEvent (1);
ce.Dispose ();
Assert.AreEqual (1, ce.CurrentCount, "#0a");
Assert.AreEqual (1, ce.InitialCount, "#0b");
Assert.IsFalse (ce.IsSet, "#0c");
try {
ce.AddCount ();
Assert.Fail ("#1");
} catch (ObjectDisposedException) {
}
try {
ce.Reset ();
Assert.Fail ("#2");
} catch (ObjectDisposedException) {
}
try {
ce.Signal ();
Assert.Fail ("#3");
} catch (ObjectDisposedException) {
}
try {
ce.TryAddCount ();
Assert.Fail ("#4");
} catch (ObjectDisposedException) {
}
try {
ce.Wait (5);
Assert.Fail ("#4");
} catch (ObjectDisposedException) {
}
try {
var v = ce.WaitHandle;
Assert.Fail ("#5");
} catch (ObjectDisposedException) {
}
}
示例8: RunCountdownEventTest0_StateTrans
// Validates init, set, reset state transitions.
private static void RunCountdownEventTest0_StateTrans(int initCount, int increms, bool takeAllAtOnce)
{
string methodParameters = string.Format("RunCountdownEventTest0_StateTrans(initCount={0}, increms={1}, takeAllAtOnce={2})", initCount, increms, takeAllAtOnce);
CountdownEvent ev = new CountdownEvent(initCount);
// Check initial count.
if (ev.InitialCount != initCount)
{
Debug.WriteLine(methodParameters);
Assert.True(false, string.Format(" > error: initial count wrong, saw {0} expected {1}", ev.InitialCount, initCount));
}
// Increment (optionally).
for (int i = 0; i < increms; i++)
{
ev.AddCount();
if (ev.CurrentCount != initCount + i + 1)
{
Debug.WriteLine(methodParameters);
Assert.True(false, string.Format(" > error: after incrementing, count is wrong, saw {0}, expect {1}", ev.CurrentCount, initCount + i + 1));
}
}
// Decrement until it hits 0.
if (takeAllAtOnce)
{
ev.Signal(initCount + increms);
}
else
{
for (int i = 0; i < initCount + increms; i++)
{
if (ev.IsSet)
{
Debug.WriteLine(methodParameters);
Assert.True(false, string.Format(" > error: latch is set after {0} signals", i));
}
ev.Signal();
}
}
// Check the status.
if (!ev.IsSet)
{
Debug.WriteLine(methodParameters);
Assert.True(false, string.Format(" > error: latch was not set after all signals received"));
}
if (ev.CurrentCount != 0)
{
Debug.WriteLine(methodParameters);
Assert.True(false, string.Format(" > error: latch count wasn't 0 after all signals received"));
}
// Now reset the event and check its count.
ev.Reset();
if (ev.CurrentCount != ev.InitialCount)
{
Debug.WriteLine(methodParameters);
Assert.True(false, string.Format(" > error: latch count wasn't correctly reset"));
}
}
示例9: TestBatcherAddAfterCancel
public void TestBatcherAddAfterCancel()
{
var evt = new CountdownEvent(1);
var scheduler = new SingleTaskThreadpoolScheduler();
var batcher = new Batcher<int>(new TaskFactory(scheduler), 5, 500, (inbox) =>
{
evt.Signal();
});
batcher.QueueObject(0);
Assert.IsTrue(evt.Wait(1000), "Batcher didn't initially run");
evt.Reset(2);
batcher.QueueObject(0);
batcher.Clear();
batcher.QueueObject(0);
Assert.False(evt.Wait(TimeSpan.FromSeconds(1.5)), "Batcher ran too many times");
Assert.True(evt.CurrentCount == 1, "Batcher never ran");
}
示例10: RunCountdownEventTest0_StateTrans
// Validates init, set, reset state transitions.
private static bool RunCountdownEventTest0_StateTrans(int initCount, int increms, bool takeAllAtOnce)
{
TestHarness.TestLog("* RunCountdownEventTest0_StateTrans(initCount={0}, increms={1}, takeAllAtOnce={2})", initCount, increms, takeAllAtOnce);
CountdownEvent ev = new CountdownEvent(initCount);
// Check initial count.
if (ev.InitialCount != initCount)
{
TestHarness.TestLog(" > error: initial count wrong, saw {0} expected {1}", ev.InitialCount, initCount);
return false;
}
// Increment (optionally).
for (int i = 0; i < increms; i++)
{
ev.AddCount();
if (ev.CurrentCount != initCount + i + 1)
{
TestHarness.TestLog(" > error: after incrementing, count is wrong, saw {0}, expect {1}", ev.CurrentCount, initCount + i + 1);
return false;
}
}
// Decrement until it hits 0.
if (takeAllAtOnce)
{
ev.Signal(initCount + increms);
}
else
{
for (int i = 0; i < initCount + increms; i++)
{
if (ev.IsSet)
{
TestHarness.TestLog(" > error: latch is set after {0} signals", i);
return false;
}
ev.Signal();
}
}
// Check the status.
if (!ev.IsSet)
{
TestHarness.TestLog(" > error: latch was not set after all signals received");
return false;
}
if (ev.CurrentCount != 0)
{
TestHarness.TestLog(" > error: latch count wasn't 0 after all signals received");
return false;
}
// Now reset the event and check its count.
ev.Reset();
if (ev.CurrentCount != ev.InitialCount)
{
TestHarness.TestLog(" > error: latch count wasn't correctly reset");
return false;
}
return true;
}
示例11: Reset_Zero
public void Reset_Zero ()
{
var ev = new CountdownEvent (1);
Assert.IsFalse (ev.IsSet, "#1");
ev.Reset (0);
Assert.IsTrue (ev.IsSet, "#2");
Assert.IsTrue (ev.Wait (0), "#3");
Assert.AreEqual (0, ev.CurrentCount, "#4");
}
示例12: Execute
public void Execute()
{
//
// CountdownEventクラスには、以下のメソッドが存在する。
// ・AddCountメソッド
// ・Resetメソッド
// AddCountメソッドは、CountdownEventの内部カウントをインクリメントする。
// Resetメソッドは、現在の内部カウントをリセットする。
//
// どちらのメソッドも、Int32を引数に取るオーバーロードが用意されており
// 指定した数を設定することも出来る。
//
// 尚、AddCountメソッドを利用する際の注意点として
// 既に内部カウントが0の状態でAddCountを実行すると例外が発生する。
// つまり、既にIsSetがTrue(シグナル状態)でAddCountするとエラーとなる。
//
//
// 内部カウントが0の状態で、AddCountしてみる.
//
using (var cde = new CountdownEvent(0))
{
// 初期の状態を表示.
PrintCurrentCountdownEvent(cde);
try
{
//
// 既にシグナル状態の場合に、さらにAddCountしようとすると例外が発生する.
//
cde.AddCount();
}
catch (InvalidOperationException invalidEx)
{
Output.WriteLine("*** {0} ***", invalidEx.Message);
}
// 現在の状態を表示.
PrintCurrentCountdownEvent(cde);
}
Output.WriteLine("");
using (var cde = new CountdownEvent(1))
{
// 初期の状態を表示.
PrintCurrentCountdownEvent(cde);
//
// 10個の別処理を実行する.
// それぞれの内部処理にてランダムでSLEEPして、終了タイミングをバラバラに設定.
//
Output.WriteLine("別処理開始・・・");
for (var i = 0; i < 10; i++)
{
Task.Factory.StartNew(TaskProc, cde);
}
do
{
// 現在の状態を表示.
PrintCurrentCountdownEvent(cde, "t");
Thread.Sleep(TimeSpan.FromSeconds(2));
} while (cde.CurrentCount != 1);
Output.WriteLine("・・・別処理終了");
//
// 待機.
//
Output.WriteLine("メインスレッドにて最後のカウントをデクリメント");
cde.Signal();
cde.Wait();
// 現在の状態を表示.
PrintCurrentCountdownEvent(cde);
Output.WriteLine("");
//
// 内部カウントをリセット.
//
Output.WriteLine("内部カウントをリセット");
cde.Reset();
// 現在の状態を表示.
PrintCurrentCountdownEvent(cde);
//
// 待機.
//
Output.WriteLine("メインスレッドにて最後のカウントをデクリメント");
cde.Signal();
cde.Wait();
// 現在の状態を表示.
PrintCurrentCountdownEvent(cde);
}
//.........这里部分代码省略.........
示例13: TestSendNotifyCore
private static void TestSendNotifyCore( IPEndPoint endPoint, CountdownEvent arrivalLatch, IProducerConsumerCollection<string> arrivedIds, int count )
{
using ( var clientTransportManager = new UdpClientTransportManager( new RpcClientConfiguration() { PreferIPv4 = true } ) )
using ( var connectTask = clientTransportManager.ConnectAsync( endPoint ) )
{
if ( !connectTask.Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) )
{
throw new TimeoutException();
}
using ( var clientTransport = connectTask.Result )
{
for ( int i = 0; i < count; i++ )
{
if ( arrivalLatch != null )
{
arrivalLatch.Reset();
}
var args = Enumerable.Repeat( 0, arrivalLatch.InitialCount ).Select( _ => Guid.NewGuid().ToString() ).ToArray();
var exceptions = new ConcurrentBag<Exception>();
if ( !Task.Factory.ContinueWhenAll(
args.Select(
arg =>
Task.Factory.StartNew(
() =>
{
var requestContext = clientTransport.GetClientRequestContext();
requestContext.SetNotification(
"Dummy",
( exception, completedSynchronously ) =>
{
if ( exception != null )
{
exceptions.Add( exception );
}
arrivalLatch.Signal();
}
);
requestContext.ArgumentsPacker.PackArrayHeader( 1 );
requestContext.ArgumentsPacker.Pack( arg );
return requestContext;
}
)
).ToArray(),
previouses =>
{
var contexts = previouses.Select( previous => previous.Result ).ToArray();
foreach ( var context in contexts )
{
clientTransport.Send( context );
}
}
).ContinueWith(
previous =>
{
if ( previous.IsFaulted )
{
throw previous.Exception;
}
// receive
if ( !arrivalLatch.Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) )
{
throw new TimeoutException( "Receive" );
}
if ( exceptions.Any() )
{
throw new AggregateException( exceptions );
}
}
).Wait( Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds ) )
{
throw new TimeoutException();
}
}
}
}
}
示例14: start
public void start()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; // used for mono certificates issues
boards = new List<string>();
boards.AddRange(config.readString("trelloBoardsToWatch", "comma,separated,list,of,board_ids").Split(','));
processingFinished = new CountdownEvent(boards.Count);
processingStarted = new CountdownEvent(boards.Count);
ApiKey = config.readString("trelloApiKey", "null");
Token = config.readString("trelloToken","null");
channel = config.readString("ircChannel", "#trello-notifications");
l_addMemberToCard = Program.localization.readString("addMemberToCard", @"[{0}] [https://trello.com/c/{1} {2} added {3} to ""{4}"" card!]");
l_commentCard = Program.localization.readString("commentCard", @"[{0}] [https://trello.com/c/{1} {2} commented on {3} card!]");
l_createCard = Program.localization.readString("createCard", @"[{0}] [https://trello.com/c/{1} {2} created ""{3}"" card in {4} list!]");
l_createList = Program.localization.readString("createList", @"[{0}] [https://trello.com/b/{1} {2} created ""{3}"" list]");
lantencyWatcher = new Stopwatch();
while(true)
{
if (!IrcClient.connected)
continue;
#if !DEBUG
Console.Clear();
#endif
ConsoleNotifications.writeNotify("Starting fetching data from trello!");
ConsoleNotifications.writeDebug("Current time before:" + DateSinceCheck);
foreach (string board in boards)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(checkForData), board);
}
processingStarted.Wait();
lantencyWatcher.Start();
ConsoleNotifications.writeNotify("All threads started!");
//getCurrentTime();
processingFinished.Wait();
ConsoleNotifications.writeNotify("All threads completed data fetch!");
lantencyWatcher.Stop();
ConsoleNotifications.writeDebug("Latency: " + lantencyWatcher.ElapsedMilliseconds + "ms");
lantencyWatcher.Reset();
processingFinished.Reset(boards.Count);
processingStarted.Reset(boards.Count);
Thread.Sleep(config.readInt("trelloFetchPeriod", 10000));
ConsoleNotifications.writeNotify("Current time after:" + DateSinceCheck);
}
}
示例15: TestEchoRequestContinuous
public void TestEchoRequestContinuous()
{
try
{
const int count = 3;
bool[] serverStatus = new bool[ count ];
string message = "Hello, world";
using ( var waitHandle = new CountdownEvent( count ) )
using ( var server =
CallbackServer.Create(
CreateConfiguration(
host => new TcpServerTransportManager( host ),
( id, args ) =>
{
try
{
Assert.That( args[ 0 ] == message );
Assert.That( args[ 1 ].IsTypeOf<Int64>().GetValueOrDefault() );
lock ( serverStatus )
{
serverStatus[ id.Value ] = true;
}
return args;
}
finally
{
waitHandle.Signal();
}
}
)
)
)
{
TestEchoRequestContinuousCore( serverStatus, waitHandle, count, message );
waitHandle.Reset();
Array.Clear( serverStatus, 0, serverStatus.Length );
// Again
TestEchoRequestContinuousCore( serverStatus, waitHandle, count, message );
}
}
catch ( SocketException sockEx )
{
Console.Error.WriteLine( "{0}({1}:0x{1:x8})", sockEx.SocketErrorCode, sockEx.ErrorCode );
Console.Error.WriteLine( sockEx );
throw;
}
}