c# - 停止线程后,可以用变量取消监听操作吗?

标签 c# sockets asyncsocket

我使用以下方法在线程中监听端口。等待 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/

相关文章:

c# - 如何使用 JSON 嵌套对象

c# - 如何 "edit"函数中的外部对象

c# - C++ 事件处理

c# - 套接字断开连接行为

ios - 如何在iOS中开发IP Messenger?

c# - Win Mobile 6.5.3 模拟器无法连接到互联网

c - 使用 epoll 的多个 UDP 套接字 - 无法接收数据

python - Twisted 是 httplib2/socket 的替代品吗?

python异步套接字编程

objective-c - AsyncSocket/GCDAsyncSocketis 的哪一部分是关于异步的?