我使用以下方法在线程中监听端口。等待 WaitOne
方法,我停止线程(我正在执行 IsCancellationRequested true)并且我无法关闭 listener
目的。然后当我想监听同一个端口时出现错误。
我可以将监听器对象绑定(bind)到变量吗?如果该变量为假,它将自动关闭。
我不想检查线程是否被单独的线程停止并关闭 listener
.
public void StartListening(Connection connection)
{
// There are codes here..
try
{
listener.Bind(localEndPoint);
listener.Listen(2);
while (connection.CancellationTokenSource.IsCancellationRequested == false)
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
allDone.WaitOne(); // While I'm waiting here, I'm making the 'IsCancellationRequested' variable true.
}
listener.Close();
}
catch (Exception e)
{
// There are codes here..
}
// There are codes here..
}
注意:
Connection
class 是我创建的包含 System.Threading.CancellationTokenSource CancellationTokenSource
的类属性(property)。
最佳答案
我不知道 connection
的精确结构, 但...
您可以尝试在两个 handle 上等待。 (未经测试)
var handles = new EventWaitHandle[]
{
allDone,
connection.CancellationTokenSource.Token.WaitHandle
};
int index = EventWaitHandle.WaitAny(handles);
WaitAny 返回设置的等待句柄的索引。所以确定你是否想打破你的时间。
也许是这样的:
public void StartListening(Connection connection)
{
// There are codes here..
try
{
listener.Bind(localEndPoint);
listener.Listen(2);
var handles = new EventWaitHandle[]
{
allDone,
connection.CancellationTokenSource.Token.WaitHandle
};
do
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
while(EventWaitHandle.WaitAny(handles) == 0);
listener.Close();
}
catch (Exception e)
{
// There are codes here..
}
// There are codes here..
}
一种取消监听器的方法。暂时无法做出更好的东西。如果有人有更好的方法......请随意;-)
ManualResetEvent _listenerTerminated = new ManualResetEvent(false);
// <snip>
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
private void AcceptCallback(IAsyncResult ar)
{
// before calling EndAccept, check an event.
if(_listenerTerminated.WaitOne(0))
return;
var clientSocket = listener.EndAccept(asyncResult);
}
// <snip>
do
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
while(EventWaitHandle.WaitAny(handles) == 0);
_listenerTerminated.Set();
listener.Close();
关于c# - 停止线程后,可以用变量取消监听操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43088857/