在.NET中使用返回值执行多线程或异步任务的最佳方法是什么?

Jef*_*eff 4 c# multithreading delegates asynchronous

在C#中,在以下情况下执行多线程或异步任务的最佳方法是什么?

简化情况:

http请求需要进行5次或更多次Web服务调用.完成后,每个Web服务调用将接收并返回字符串列表作为结果.调用者(5个Web服务调用)需要将5个结果合并为单个字符串列表并将其返回给http调用者.

因为每个线程都需要在最后返回一个值,所以我想知道是否可以使用异步委托.因为我在这方面不是很有经验所以我问这个问题和/或建议.

谢谢!

Jam*_*mes 5

您应该看看QueueUserWorkItem.这将允许您在单独的线程上执行每个调用,并根据特定的调用获取字符串值,例如

ManualResetEvent[] calls = new ManualResetEvent[5];
string[] results = new string[5];

calls[0] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(t => 
{
    results[0] = // do webservice call
    calls[0].Set();
});

calls[1] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(t => 
{
    results[1] = // do webservice call
    calls[1].Set();
});

....
// wait for all calls to complete
WaitHandle.WaitAll(calls);
// merge the results into a comma delimited string
string resultStr = String.Join(", ", results);
Run Code Online (Sandbox Code Playgroud)