venerdì 9 marzo 2018

Chiamare un web service in modalità asincrona e sincrona in c#

Il seguente esempio è una chiamata ad un metodo di un web service in c# con una risposta in modalità sincrona o asincrona.

Decommentando la parte di wait response si potrà attendere l'esito, altrimenti verrà restituito un risultato mentre l'elaborazione sarà in corso.
public class ServiceExample : System.Web.Services.WebService
    {
 private delegate string AsyncMethodCallerCreateZip(string idArticle, out string outResult);
  
 [WebMethod(Description = "An example")]
 public string FirstElaboration(string idArticle)
 {
  try
  {
   //Async call
   AsyncMethodCallerCreateZip caller = new AsyncMethodCallerCreateZip(CreateZip);
   IAsyncResult result = caller.BeginInvoke(idArticle, out outResult, null, null);

   //wait response
   //result.AsyncWaitHandle.WaitOne();
   //string returnValue = caller.EndInvoke(out outResult, result);
   //result.AsyncWaitHandle.Close();
   //return returnValue;

   return "OK";
  }
  catch (Exception ex)
  {
   return "KO";
  }
 }

 public string CreateZip(string idArticle, out string outResp)
 {
  //code here
  return outResp;
 }
}