Richiamo di una chiamata asincrona in un servizio Web C #
-
05-07-2019 - |
Domanda
Sto consumando una risorsa di terze parti (una .dll) in un servizio web e il mio problema è che invocare questa risorsa (chiamando un metodo) è fatto in modo asincrono - per ottenere un abbonamento devo ottenere la risposta per la mia richiesta. Come posso farlo in un servizio web c #?
Aggiornamento:
Per quanto riguarda Risposta di Sunny :
Non voglio rendere il mio servizio Web asincrono.
Soluzione
Se il componente di terze parti non supporta il modello di programmazione asincrona standard (ovvero non utilizza IAsyncResult), è comunque possibile ottenere la sincronizzazione utilizzando AutoResetEvent o ManualResetEvent. Per fare ciò, dichiarare un campo di tipo AutoResetEvent nella classe del servizio Web:
AutoResetEvent processingCompleteEvent = new AutoResetEvent();
Quindi attendi che l'evento venga segnalato dopo aver chiamato il componente di terze parti
// call 3rd party component
processingCompleteEvent.WaitOne()
E nel gestore dell'evento callback segnala l'evento per consentire l'esecuzione del thread in attesa:
processingCompleteEvent.Set()
Altri suggerimenti
Supponendo che il tuo componente di terze parti stia utilizzando il modello di modello di programmazione asincrono utilizzato in .NET Framework, potresti fare qualcosa del genere
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();
}
Poiché è necessario bloccare l'operazione del servizio Web, è necessario utilizzare IAsyncResult.AsyncWaitHandle anziché il callback per bloccare fino al completamento dell'operazione.
Da Documenti 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);
}
}