How to invoke asynchronously the WCF service method with WebInvokeAttribute?

advertisements

I have WCF Service with this one method. That method has WebInvoke Attribute. How can I call it asynchronously?

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

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


You could define asynchronous behavior to your service class, by passing following values together to ServiceBehavior attribute:

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

The resulting code might look like following:

[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");
    }
}