c#await websocket read async在Task.Run中不起作用

时间:2016-06-05 19:29:26

标签: c# asynchronous

这是一个演示此问题的简单演示。如果我使用Task.Run在Client的类构造函数中启动监听方法,则监听方法中等待的值将永远不会被填满。如果我在当前线程上运行该方法,而不等待它,它将正常工作。到底是怎么回事 ?

using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using System.Net.WebSockets;
using System.Threading;
using System.Text;

namespace WebAgent
{
    public class Startup
    {
        Client client = null;
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            //app.UseRemotoWebSocketServer();
            app.UseWebSockets();
            app.Use(async (http, next) =>
            {
                WebSocket webSocket = null;
                if (http.WebSockets.IsWebSocketRequest)
                {
                    webSocket = await http.WebSockets.AcceptWebSocketAsync();
                    if (webSocket != null && webSocket.State == WebSocketState.Open)
                    {
                        client = new Client(webSocket, 0);
                    }
                }
                else
                {
                    // Nothing to do here, pass downstream.  
                    await next();
                }
            });
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(@"
                <!DOCTYPE html>
                <html>
                    <head>
                        <meta charset=""utf-8"" />
                         <script type=""text/javascript"">
                            var conn = null;
                            document.addEventListener(""DOMContentLoaded"", function(event){
                                var conn = new WebSocket(""ws://localhost:5000/"");
                                conn.onmessage = function(pMessage) {
                                    alert(pMessage.data);
                                };
                                document.onclick = function(e) {
                                    conn.send(""Hello !"");
                                };
                            });
                         </script>
                    </head>
                    <body>test</body>
                </html>");
            });
        }

        // Entry point for the application.
        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }


    public class Client
    {
        WebSocket _webSocket;
        int _id = 0;

        public Client(WebSocket pWebSocket, int pId)
        {
            _webSocket = pWebSocket;
            _id = pId;

            //THIS DOES NOT WORK
            Task.Run(this.StartReception);

            //THIS WORKS PERFECTLY
            //this.StartReception();
        }

        private async Task StartReception()
        {
            ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[4096]);
            //result will never be fulfilled 
            WebSocketReceiveResult result = await _webSocket.ReceiveAsync(buffer, CancellationToken.None);
            if(_webSocket.State == WebSocketState.Open)
            {
                string request = Encoding.UTF8.GetString(buffer.Array,
                                           buffer.Offset,
                                           buffer.Count);
            }
            if (_webSocket.State == WebSocketState.Open)
                this.StartReception();
        }
    }
}

0 个答案:

没有答案