Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 反序列化挂起整个线程_C#_Xmlserializer_Binaryformatter - Fatal编程技术网

C# 反序列化挂起整个线程

C# 反序列化挂起整个线程,c#,xmlserializer,binaryformatter,C#,Xmlserializer,Binaryformatter,我有两个通过命名管道连接的简单应用程序。在客户端,我有一种每n毫秒检查传入消息的方法: private void timer_Elapsed(Object sender, ElapsedEventArgs e) { IFormatter f = new BinaryFormatter(); try { object temp = f.Deserialize(pipeClient); //hangs here resu

我有两个通过命名管道连接的简单应用程序。在客户端,我有一种每n毫秒检查传入消息的方法:

private void timer_Elapsed(Object sender, ElapsedEventArgs e)
{
      IFormatter f = new BinaryFormatter();
      try
      {
           object temp = f.Deserialize(pipeClient); //hangs here
           result = (Func<T>)temp;
      }
      catch
      {
      }
}
private void timer\u已过(对象发送方,ElapsedEventArgs e)
{
IFormatter f=新的二进制格式化程序();
尝试
{
object temp=f.Deserialize(pipeClient);//挂起在这里
结果=(函数)温度;
}
抓住
{
}
}
在开始时,管道是空的,而f.反序列化方法挂起整个应用程序。我甚至不能检查那管子是空的?这个问题有什么解决办法吗


UPD:尝试了XmlSerializer,一切都一样。

挂在你头上的是
pipeClient.Read(
调用两个格式化程序都在内部进行

这是
在调用时的预期行为:

返回值
类型:
System.Int32

读入缓冲区的总字节数。这可能小于字节数 如果该字节数当前不可用,则请求;如果当前不可用,则请求0 到了小溪的尽头

因此,流将阻塞,直到数据显示为止,或者如果它是支持超时的流类型,则会引发超时异常。它不会在不读取任何内容的情况下返回,除非您处于“流的末尾”,而对于
管道流
(或者类似的
网络流
),只有在连接关闭时才会发生

解决问题的方法是,不要使用计时器检查是否有新消息到达,只需启动后台线程并使其处于循环中,它将阻止自己,直到消息显示

class YourClass
{
    public YourClass(PipeStream pipeClient)
    {
        _pipeClient = pipeClient;
        var task = new Task(MessageHandler, TaskCreationOptions.LongRunning);
        task.Start();
    }

    //SNIP...

    private void MessageHandler()
    {
        while(_pipeClient.IsConnected)
        {
            IFormatter f = new BinaryFormatter();
            try
            {
                 object temp = f.Deserialize(_pipeClient);
                 result = (Func<T>)temp;
            }
            catch
            {
                //You really should do some kind of logging.
            }
        }
    }
}
classyourclass
{
公共类(PipeStream pipeClient)
{
_pipeClient=pipeClient;
var task=新任务(MessageHandler,TaskCreationOptions.LongRunning);
task.Start();
}
//剪断。。。
私有void MessageHandler()
{
而(_pipeClient.IsConnected)
{
IFormatter f=新的二进制格式化程序();
尝试
{
对象temp=f.反序列化(_pipeClient);
结果=(函数)温度;
}
抓住
{
//你真的应该做一些记录。
}
}
}
}

启动后台线程以检查pipe@antlersoft当然,它挂在后台线程,直到在PiPEFI上有可用的数据为止,截至2020版本,MS建议在您的代码中。事实上,它不允许在ASP.NET中使用。相反,考虑使用JSONSerialSuxor或XMLSerialZista.有关更多信息,请参见.