【问题标题】:WCF: Simple async request and response exampleWCF:简单的异步请求和响应示例
【发布时间】:2014-08-17 12:27:19
【问题描述】:

我一直在尝试学习 WCF,并创建了 hello world 服务来查询值并返回结果。我为服务(windows phone)创建了一个客户端,向服务器发送一个值并显示结果。虽然我试图在我的 web 服务中返回字符串,但 windows phone 应用程序中方法的返回类型是 void 并且也是异步的。

public class Service1 : IService1
{
    public string GetName(String PhoneNumber)
    {
        DBEntities Context = new DBEntities();
        String Name = (from x in Context.Contacts
                       where x.Number.Equals(PhoneNumber)
                       selectx.Name).FirstOrDefault();
        return Name;
    }
 ...
}

在客户端:

private void Submit_Click(object sender, RoutedEventArgs e)
{
    ServiceReference1.Service1Client vv = new ServiceReference1.Service1Client();
    vv.GetNameAsync(TextBox1.Text);
}

我的问题是,我怎样才能从异步方法中获得响应?

【问题讨论】:

    标签: c# wcf


    【解决方案1】:

    WCF 异步操作可以使用以下三种方法之一来实现:

    1. 基于任务的异步模式
    2. 基于事件的异步模式
    3. IAsyncResult 异步模式

    那么如何编写客户端代码,取决于你如何实现 WCF 服务。基于任务的异步模式是实现异步操作的首选方式,因为它最简单、最直接。

    如果使用任务,客户端代码可能是这样的:

        Task<T> results = await vv.GetNameAsync(TextBox1.Text);
        T result = results.Result;
        if (result.Success)
        {
           // Do something with result
        }
    

    您还需要使 WCF 服务异步,这篇 MSDN 文章 How to: Implement an Asynchronous Service Operation 有一个很好的例子。

    请阅读Synchronous and Asynchronous Operations了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多