【发布时间】:2014-05-15 02:17:21
【问题描述】:
我想向远程服务发出多个请求,并且正在尝试异步/多线程方法。 对于并发部分,我会试试这个http://coding-time.blogspot.pt/2008/03/implement-your-own-parallelfor-in-c.html
IList<string> returnedValues = new List<string>();
int numberOfRequests = 5;
object sync = new object();
ParallelUtilities.For(0, numberOfRequests, delegate(int i)
{
string response = string.Empty;
try
{
try
{
Func<int, string> caller = CallService;
IAsyncResult result = caller.BeginInvoke(i, null, null);
Thread.Sleep(0);
string returnValue = caller.EndInvoke(result);
lock (sync)
{
returnedValues.Add(returnValue);
}
}
catch (Exception ex)
{
Console.WriteLine(string.Concat("ex: ", ex.Message, "stack:", ex.StackTrace));
}
});
}
还有服务调用
private string CallService(int index)
{
string value;
using (var channel = GetClientChannel<IService>("http://localhost:51383/Service/Service.svc"))
{
value = channel.GetValue(index);
}
return value + "for this index:" + index;
}
有没有更好的方法来做到这一点? IAsyncResult 如何在多线程中工作?
【问题讨论】:
标签: multithreading web-services asynchronous .net-3.5