[英]Async requests to a web service
如何从线程向Web服务发出异步请求?
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:- 在对Client对象调用
Async
方法之前,请确保未在UI线程上运行:-
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. 现在,相应的完成事件将在
ThreadPool
线程而不是UI线程上发生。
Here is a solution using WCF. 这是使用WCF的解决方案。
Service Code FileService.svc 服务代码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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.