[英]How to wait for ManualResetEvent.WaitOne() to be reached before moving on?
I'm trying to use ManualResetEvent to make a semaphore-like situation and I have placed WaitOne
, Set
and Reset
in their right places. 我正在尝试使用ManualResetEvent发出类似信号灯的情况,并且将WaitOne
, Set
和Reset
放置在正确的位置。 The WaitOne
instruction is called in a listener thread and is places right after a tcp reading: 在侦听器线程中WaitOne
指令,该指令位于tcp读取之后:
var networkStream = _clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, Convert.ToInt32(_clientSocket.ReceiveBufferSize));
_mainthreadControl.WaitOne(Timeout.Infinite);
And Set
and Reset
instructions are called in another thread, so the socket won't get competed over: 而且Set
和Reset
指令是在另一个线程中调用的,因此套接字不会引起竞争:
try
{
//some code
_mainthreadControl.Reset();
//some code that uses the same socket as above
_mainthreadControl.Set();
}
catch (Exception ex)
{
//ignored
}
But I need the code to stop when it reaches Reset
, and only continue after the WaitOne
is reached (and executed), so the code below Reset
only runs after the competing thread is waiting. 但是我需要代码在达到Reset
时停止,并且仅在到达(并执行) WaitOne
之后才继续,因此Reset
下面的代码仅在竞争线程正在等待之后运行。
I don't know if I was clear enough, so I'm glad to add details as needed. 我不清楚我是否足够清楚,因此很高兴根据需要添加详细信息。 Thanks in advance. 提前致谢。
If it suites for you. 如果适合您。 Please try to use additional AutoResetEvent. 请尝试使用其他AutoResetEvent。 Like this: 像这样:
var _additionalControl = new AutoResetEvent(false);
// code gap
var networkStream = _clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, Convert.ToInt32(_clientSocket.ReceiveBufferSize));
_additionalControl.Set();
_mainthreadControl.WaitOne(Timeout.Infinite);
// code gap
try
{
//some code
_mainthreadControl.Reset();
_additionalControl.WaitOne(Timeout.Infinite);
//some code that uses the same socket as above
_mainthreadControl.Set();
}
catch (Exception ex)
{
//ignored
}
In turn I recommend to use System.Threading.Monitor
class, cause it's more faster than ManualResetEvent(false), because it's restricted by the single process. 反过来,我建议使用System.Threading.Monitor
类,因为它比ManualResetEvent(false)更快,因为它受单个进程的限制。 If course if you don't need to use lock in another program. 当然,如果您不需要在另一个程序中使用锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.