How to call asynchronously WCF Service method with WebInvokeAttribute?

1.3k Views Asked by At

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

There are 3 best solutions below

0
On BEST ANSWER

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

You can call it asynchronously using Task Parallel Library or TPL. Here's an example. Sample code is calling WebGet. WebInvoke or HTTP Post code has some diffirence. Note that TPL is only available from .NET Framework 3.5 and higher

Add using System.Threading.Tasks; to your usings

  //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();
1
On

You can use a Thread in your client when you call that method. But for a response more precise, define the client: wich technology is used, etc.