C#SoapFormatter阻塞

时间:2018-04-11 07:52:01

标签: c# soap

我在C#中有一个客户端服务器应用程序,用于将对象从客户端发送到服务器并返回。 当服务器断开连接时,客户端线程仍然在Deserialize方法上处于阻塞模式。我怎样才能"通知"客户端关闭流并停止阻止服务器关闭时反序列化?

这是我的客户端处理程序:

public void ConnectToServer(string alias, string color)
{
    try
    {
        client = new TcpClient();

        MyMessage firstMsg = new MyMessage();
        firstMsg.Message = "MyNewClient";
        firstMsg.SenderName = alias;
        firstMsg.ClientColor = color;

        client.Connect(ep);
        isClientConnected = true;

        stream = client.GetStream();
        formatter = new SoapFormatter();

        formatter.Serialize(stream, firstMsg);

        new Thread(() =>
        {
            while (true)
            {
                try
                {
                    MyMessage msg = (MyMessage)formatter.Deserialize(stream);
                    GotMessage?.Invoke(msg);
                }
                catch (Exception)
                {
                    Debug.Write("ConnectToServer():: failed to deserialize");
                }      
            }
        }).Start();
    }
    catch (Exception)
    {
        throw new Exception("Server is offline. Try again later");
    }
}

0 个答案:

没有答案