문제

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");
}
도움이 되었습니까?

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

다른 팁

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top