[英]Async requests to a web service
如何從線程向Web服務發出異步請求?
這是簡短的答案,沒有很多解釋。
在對Client對象調用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.