我正在使用Web服务中的第三方资源(.dll),我的问题是,调用此资源(调用方法)是异步完成的 - 我需要订阅一个事件,以获取我的要求的答案。我如何在c#Web服务中执行此操作?

<强>更新

关于 Sunny的回答

我不想让我的网络服务异步。

有帮助吗?

解决方案

如果第三方组件不支持标准异步编程模型(即它不使用IAsyncResult),您仍然可以使用AutoResetEvent或ManualResetEvent实现同步。为此,请在Web服务类中声明AutoResetEvent类型的字段:

AutoResetEvent processingCompleteEvent = new AutoResetEvent();

然后在调用第三方组件

后等待事件发出信号
// call 3rd party component
processingCompleteEvent.WaitOne()

在回调事件处理程序中发出事件让等待线程继续执行:

 processingCompleteEvent.Set()

其他提示

假设您的第三方组件正在使用整个.NET Framework中使用的异步编程模型模式,您可以执行类似这样的操作

    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.stackoverflow.com");
    IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(null, null);

    asyncResult.AsyncWaitHandle.WaitOne();

    using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult))
    using (StreamReader responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream()))
    {
        string responseText = responseStreamReader.ReadToEnd();
    }

由于您需要阻止Web服务操作,因此应该使用IAsyncResult.AsyncWaitHandle而不是回调来阻止操作完成。

来自 MSDN docs

using System;
using System.Web.Services;

[WebService(Namespace="http://www.contoso.com/")]
public class MyService : WebService {
  public RemoteService remoteService;
  public MyService() {
     // Create a new instance of proxy class for 
     // the XML Web service to be called.
     remoteService = new RemoteService();
  }
  // Define the Begin method.
  [WebMethod]
  public IAsyncResult BeginGetAuthorRoyalties(String Author,
                  AsyncCallback callback, object asyncState) {
     // Begin asynchronous communictation with a different XML Web
     // service.
     return remoteService.BeginReturnedStronglyTypedDS(Author,
                         callback,asyncState);
  }
  // Define the End method.
  [WebMethod]
  public AuthorRoyalties EndGetAuthorRoyalties(IAsyncResult
                                   asyncResult) {
   // Return the asynchronous result from the other XML Web service.
   return remoteService.EndReturnedStronglyTypedDS(asyncResult);
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top