Search code examples
c#wcfasynchronouswebinvoke

How to call asynchronously WCF Service method with WebInvokeAttribute?


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

Solution

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