Question

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");
}
Was it helpful?

Solution 2

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

OTHER TIPS

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.

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top