用法:

            Socket server;
            while (!this.IsDisposed && (server = this._server) != null)
            {
                Socket socket = await AcceptYield(server);
                if (socket == null)
                {
                    continue;
                }
                // TODO: Your are code here.
            }

实现: 

#if NETCOREAPP
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
        public static Task<Socket> AcceptYield(Socket socket)
        {
            TaskCompletionSource<Socket> tcs = new TaskCompletionSource<Socket>();
            IAsyncResult r = null;
            if (socket != null)
            {
                try
                {
                    r = socket.BeginAccept(ar =>
                    {
                        try
                        {
                            tcs.SetResult(socket.EndAccept(ar));
                        }
                        catch
                        {
                            tcs.SetResult(null);
                        }
                    }, null);
                }
                catch { }
            }
            else { }
            if (r == null)
            {
                tcs.SetResult(null);
            }
            return tcs.Task;
        }

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐