Async requests to a web service

心已入冬 提交于 2019-12-29 09:40:07

问题


How to make async requests to a webservice from a Thread?


回答1:


Here is the short answer without a load of explanations.

Before calling the Async method on your Client object make sure you are not running on the UI Thread:-

System.Threading.ThreadPool.QueueUserWorkItem( o =>
{
   try
   {
      svc.SomeMethodAsync();
   }
   catch (err)
   {
       // do something sensible with err
   }
});

Now the corresponding completed event will occur on a ThreadPool thread not the UI Thread.




回答2:


Here is a solution using WCF.

Service Code FileService.svc

public class FileService
{
    [OperationContract]
    public byte[] GetFile(string filename)
    {
        byte[] File;
        //do logic

        return File;
    }
}

Client Code

public int requested_file_count = 5;
public list<string> filenames;

public FileServiceClient svc 

//Constructor
public Example()
{
   svc = new FileServiceClient();
} 

Public void GetFiles()
{
    //Initialise the list of names and set the count of files received     
    filenames = new list<string>(5);
    requested_file_count = filenames.Count; 

   svc.GetFileCompleted += new EventHandler<GetFileCompletedEventArgs>(GetFile_Completed);

   //Call the Async Method passing it the file name and setting the userstate to 1;

   svc.GetFileAsync(filenames[0],1);
}

void GetFile_Completed(object Sender, GetFileCompletedEventArgs e)
{
   if (e.UserState == requested_file_count)
   {
     //All files have been downloaded
   }
   else
   {
      svc.GetFileAsync(filenames[e.UserState],++e.UserState);
   }

   //Do Something with the downloaded file
   byte[] filedata = e.result;
}


来源:https://stackoverflow.com/questions/6824112/async-requests-to-a-web-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!