场景:有一个请求和许多供应商,因此从我使用的所有供应商处获得结果,
var supplierResults = suppliers.AsParallel()
.WithDegreeOfParallelism(suppliers.Count())
.Select(supplier => supplier.GetResponse(request, SuppliersRequestTimespan))
.ToArray();
Task.WaitAll(supplierResults);
哪种工作正常。
在另一个场景中,我有三个不同的请求,并希望同时发送给所有供应商(线程)。我只是尝试如下:
int TaskCount = 3;
var tasks = new Task[TaskCount];
tasks[0] = Task.Factory.StartNew(() => (suppliers.AsParallel()
.WithDegreeOfParallelism(suppliers.Count())
.Select(supplier => supplier.GetResponse(request1, SuppliersRequestTimespan))
.ToArray()));
tasks[1] = Task.Factory.StartNew(() => (suppliers.AsParallel()
.WithDegreeOfParallelism(suppliers.Count())
.Select(supplier => supplier.GetResponse(request2, SuppliersRequestTimespan))
.ToArray()));
tasks[2] = Task.Factory.StartNew(() => (suppliers.AsParallel()
.WithDegreeOfParallelism(suppliers.Count())
.Select(supplier => supplier.GetResponse(request3, SuppliersRequestTimespan))
.ToArray()));
Task.WaitAll(tasks);
但是,不幸的是它不会'等待'回应。
GetResponse()
方法来自界面,如下所示:
public interface ISupplier
{
Task<JObject> GetResponse(JObject request, TimeSpan timeout);
Task<JObject> GetResponseAsync(JObject request, TimeSpan timeout);
string GetSupplierBrand();
string GetSupplierCulture();
}
希望你们帮助我完成这个......
答案 0 :(得分:0)
尝试使用Microsoft的Reactive Framework。
这是主要代码:
var requests = new[] { request1, request2, request3 };
var query =
from supplier in suppliers.ToObservable()
from request in requests.ToObservable()
from response in Observable.FromAsync(() =>
supplier.GetResponseAsync(request, SuppliersRequestTimespan))
select new { supplier, request, response };
现在,如果您希望将所有结果作为数组获取,请调用:
var results = query.ToArray().Wait();
但您可以随时使用Reactive Framework获取每个结果。只需执行此操作:
var subscription =
query
.Subscribe(result =>
{
// Do something with each result
});
所有这些都是多线程的,并使用最大可用线程数。
这太简单了。