What is a good way to shutdown Threads blocked on NamedPipeServer#WaitForConnection?

后端 未结 7 2380
误落风尘
误落风尘 2020-12-01 10:02

I start my application which spawns a number of Threads, each of which creates a NamedPipeServer (.net 3.5 added managed types for Named Pipe IPC) and waits for clients to

相关标签:
7条回答
  • 2020-12-01 11:01

    I wrote this extension method to solve this problem:

    public static void WaitForConnectionEx(this NamedPipeServerStream stream)
    {
        var evt = new AutoResetEvent(false);
        Exception e = null;
        stream.BeginWaitForConnection(ar => 
        {
            try
            {
                stream.EndWaitForConnection(ar);
            }
            catch (Exception er)
            {
                e = er;
            }
            evt.Set();
        }, null);
        evt.WaitOne();
        if (e != null)
            throw e; // rethrow exception
    }
    
    0 讨论(0)
提交回复
热议问题