C#Webサービスで非同期呼び出しを呼び出す
-
05-07-2019 - |
質問
Webサービスでサードパーティのリソース(.dll)を消費していますが、このリソースの呼び出し(メソッドの呼び出し)が非同期で行われる-イベントをサブスクライブする必要があります私の要求に対する答え。 C#Webサービスでそれを行うにはどうすればよいですか?
更新:
Webサービスを非同期にしたくない。
解決
サードパーティのコンポーネントが標準の非同期プログラミングモデルをサポートしていない(つまり、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ドキュメントから:
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);
}
}
所属していません StackOverflow