【问题标题】:How to call asynchronously WCF Service method with WebInvokeAttribute?如何使用 WebInvokeAttribute 异步调用 WCF 服务方法?
【发布时间】:2012-12-30 20:42:53
【问题描述】:

我有使用这种方法的 WCF 服务。该方法具有 WebInvoke 属性。如何异步调用它?

[WebInvoke(UriTemplate = "*", Method = "*")]
public Message HandleRequest()
{
    var webContext = WebOperationContext.Current;
    var webClient = new WebClient();

    return webContext.CreateStreamResponse(webClient.OpenRead("http://site.com"), "text/html");
}

【问题讨论】:

  • 该方法通常由 REST 服务使用。 WebInvoke 通过 Http "POST" 方法调用,而 WebGet 是 Http "GET"。您指的是 REST 服务吗?
  • 是的,REST 服务。我通过浏览器使用此服务。

标签: c# wcf asynchronous webinvoke


【解决方案1】:

您可以通过将以下值一起传递给ServiceBehavior 属性来为您的服务类定义异步行为:

  1. InstanceContextMode = InstanceContextMode.Single,
  2. ConcurrencyMode = ConcurrencyMode.Multiple.

生成的代码可能如下所示:

[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class MyService
{
    [WebInvoke(UriTemplate = "*", Method = "*")]
    public Message HandleRequest()
    {
        var webContext = WebOperationContext.Current;
        var webClient = new WebClient();

        return webContext.CreateStreamResponse(webClient.OpenRead("http://site.com"), "text/html");
    }
}

【讨论】:

    【解决方案2】:

    您可以使用任务并行库或 TPL 异步调用它。这是一个例子。示例代码正在调用 WebGet。 WebInvoke 或 HTTP Post 代码有一些不同。请注意,TPL 仅适用于 .NET Framework 3.5 及更高版本

    使用 System.Threading.Tasks 添加;到你的用途

      //URL that points to your REST service method
                    var request = WebRequest.Create(url);                   
                    var task = Task.Factory.FromAsync<WebResponse>(
                                request.BeginGetResponse,
                                request.EndGetResponse,
                                null);
                    var dataStream = task.Result.GetResponseStream();
                    var reader = new StreamReader(dataStream);
                    var responseFromServer = reader.ReadToEnd();
                    reader.Close();
                    dataStream.Close();
    

    【讨论】:

      【解决方案3】:

      当您调用该方法时,您可以在客户端中使用线程。 但要获得更精确的响应,请定义客户端:使用哪种技术等。

      【讨论】:

      • 您无法使用浏览器进行异步调用。你为什么要这么做?
      猜你喜欢
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      相关资源
      最近更新 更多