Task.Factory.StartNew正在阻止UI线程

我有一个C#桌面应用程序,一个客户端服务器应用程序。我试图在客户端异步进行接收,并为此创建新任务。一切正常,消息双向传播,但是当消息进入View时,它只是阻塞。我已经搜索并尝试了2个小时的静态异步方法,然后等待,但是对我没有任何帮助...这是我的客户代码:

public class Connection
    {
        private static Socket serverSocket;
        private BaseHandler baseHandler;
        public Connection(BaseHandler baseHandler)
        {
            this.baseHandler = baseHandler;
            IPHostEntry host = Dns.GetHostEntry("localhost");
            IPAddress ipAddress = host.AddressList.First();
            IPEndPoint serverEndpoint = new IPEndPoint(ipAddress, 9000);

            if (serverSocket == null)
            {
                serverSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Connect(serverEndpoint);
                Console.WriteLine($"Successfully connected to server on: {serverSocket.RemoteEndPoint}");
            }
            Task.Factory.StartNew(() => receiveMessage());
        }

        public void receiveMessage()
        {
            Message receivedMessage = null;
            var buffer = new byte[2048 * 2];
            int bytesReceived = 0;
            while (true)
            {
                if (serverSocket.Available != 0)
                {
                    bytesReceived = serverSocket.Receive(buffer);

                    if (bytesReceived != 0)
                    {
                        receivedMessage = (Message)Serializer.FromStream(new MemoryStream(buffer));
                        Console.WriteLine($"Received message: {receivedMessage.Content}");

                        //handle message
                        baseHandler.handle(receivedMessage);
                    }
                }
                Thread.Sleep(100);
            }
        }

        public void SendMessage(Message msg)
        {
            Console.WriteLine($"Sending msg with content : {msg.Content}");
            MemoryStream stream = Serializer.ToStream(msg);
            var bytesSent = serverSocket.Send(stream.GetBuffer());

            Console.WriteLine("Waiting to receive");
        }
    }

并且鉴于:

public void showErrorMessage(String err)
        {
            messageLog.StringValue = err; //either of this two methods are blocking... 
        }

        public void openWindow()
        {
            var storyboard = NSStoryboard.FromName("Main", null);
            var controller = storyboard.InstantiateControllerWithIdentifier("UserView") as NSWindowController;
            controller.ShowWindow(this);
        }

有人有主意吗?

评论