How to call an asynchronous WCF service method using WebInvokeAttribute?

I have a WCF service using this method. This method has a 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"); } 
+4
source share
3 answers

You can define asynchronous behavior for your service class by passing the following values ​​along with the ServiceBehavior attribute:

  • InstanceContextMode = InstanceContextMode.Single ,
  • ConcurrencyMode = ConcurrencyMode.Multiple .

The resulting code may look like this:

 [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
source

You can use Thread in your client when you call this method. But for a more accurate answer, identify the client: what technology is used, etc.

+1
source

You can call it asynchronously using a parallel task library or TPL. Here is an example. The sample code calls WebGet. WebInvoke or HTTP zip code has some differences. Please note that TPL is only available from the .NET Framework 3.5 and higher.

Add using System.Threading.Tasks; to your needs

  //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(); 
0
source

All Articles