Async requests to a web service

前端 未结 2 342
抹茶落季
抹茶落季 2020-12-22 10:37

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

2条回答
  •  囚心锁ツ
    2020-12-22 11:39

    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 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(5);
        requested_file_count = filenames.Count; 
    
       svc.GetFileCompleted += new EventHandler(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;
    }
    

提交回复
热议问题