对web服务的异步请求

本文关键字:异步 请求 服务 web | 更新日期: 2023-09-27 18:03:45

如何从线程向web服务发出异步请求?

对web服务的异步请求

这是一个简短的答案,没有大量的解释。

在你的客户端对象上调用Async方法之前,确保你没有在UI线程上运行:-

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

现在相应的完成事件将发生在ThreadPool线程上,而不是UI线程上。

这是一个使用WCF的解决方案。

服务代码FileService.svc

public class FileService
{
    [OperationContract]
    public byte[] GetFile(string filename)
    {
        byte[] File;
        //do logic
        return File;
    }
}
客户机代码

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;
}