【问题标题】:Calling an async WCF method throws an exception调用异步 WCF 方法会引发异常
【发布时间】:2017-08-17 13:29:40
【问题描述】:

我有一个需要转换视频的 WCF 服务。我需要从我的 Xamarin 应用程序中调用该方法。如果我调用常规方法,一切都会按预期工作,但如果我调用 Async 方法,则会收到以下错误。 我已经将 WCF 服务上的 IncludeExceptionDetailInFaults 设置为 true,以获取错误的详细信息。

WCF:

界面:

[ServiceContract]
public interface IConvert
{
    [OperationContract]
    bool ConvertVideo(string path);
}

服务:

public class ConvertService : IConvert
{
    public bool ConvertVideo(string path)
    {
        Console.WriteLine("Converting video... wait 3 sec");
        Thread.Sleep(3000);
        Console.WriteLine("Video converted!");
        Console.WriteLine(path);

        return true;
    }
}

Xamarin:

这行得通:

try
{
    _Client.ConvertVideo(GetFullFtpPath());
}
catch (Exception e) { }

这会引发错误:

try
{
    _Client.ConvertVideoAsync(GetFullFtpPath());
}
catch (Exception e) { }

错误:

{System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: 
Error in deserializing body of request message for operation 'ConvertVideo'. 
OperationFormatter encountered an invalid Message body. 
Expected to find node type 'Element' with name 'ConvertVideo' and namespace 'http://tempuri.org/'. 
Found node type 'Element' with name 'ConvertVideoAsync' and namespace 'http://tempuri.org/' 
(Fault Detail is equal to Error in deserializing body of request message for operation 'ConvertVideo'. 
OperationFormatter encountered an invalid Message body. 
Expected to find node type 'Element' with name 'ConvertVideo' and namespace 'http://tempuri.org/'. 
Found node type 'Element' with name 'ConvertVideoAsync' and namespace 'http://tempuri.org/').}

编辑:这只发生在 Xamarin 上。我已经用 WPF 尝试过,一切正常。

【问题讨论】:

  • 你能解决这个问题吗?我在这里遇到同样的错误。对于 Xamarin Android,它只生成 Async 方法。这很奇怪,因为我只在 Xamarin Forms netstandard 版本上收到此错误,而不是以前的 PCL 版本。
  • @hushyon 不,这种方法似乎不适用于 Xamarin。我实施了一种解决方法,我每隔几秒钟轮询一次服务器。更优雅的方法是实现 SignalR 用于与服务器的通信,而不需要轮询。

标签: c# wcf xamarin service


【解决方案1】:

您的 _Client 应该有 _Client.ConvertVideoCompleted。你的代码应该是这样的

try
{
 _Client.ConvertVideoCompleted+= yourHandler;
  _Client.ConvertVideo(GetFullFtpPath());
}
catch (Exception e) { }

参考https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-call-wcf-service-operations-asynchronously

【讨论】:

  • 这不会消除错误。您的解决方案只让我知道任务何时完成,但错误仍然存​​在。
  • 我现在看到它可以在 WPF 中使用。在这种情况下,您是否在 Xamrin 客户端和 WPF 客户端中使用相同的代理类?
  • 是的,我在这两种情况下都使用相同的代理类。这很奇怪,因为我可以从 Xamarin 调用常规方法,但是当我尝试调用 Async 方法时出现错误。
猜你喜欢
  • 1970-01-01
  • 2012-01-01
  • 1970-01-01
  • 2011-09-24
  • 2011-07-19
  • 2020-11-07
  • 1970-01-01
相关资源
最近更新 更多