Reputation: 48197
I need to do something like this Test() is just calculations, I only want to put all cpu core at work to find the solution faster.
for (int i= 0; i<1000000; i++)
{
result[i] = Test(i);
if (result[i] == 0)
{
break;
}
}
I have work with BackgroundWorker before. And could create an array of N bgWorker and handle a queue by myself but looks too much trouble.
So I found Task.Factory, seem similar to what I want, but still don't know how handle each separate task to wait for the result and stop everything when found the asnwer.
Task<string> task = Task.Factory.StartNew<string>
(() => DownloadString("http://www.google.com/"));
string result = task.Result;
Or maybe is there other solution for my problem.
Upvotes: 2
Views: 92
Reputation: 149538
You actually don't need to put multiple cores to use since you're doing IO bound work.
You could take advantage of naturally async APIs for HTTP requests, such as those exposed by HttpClient
. Then, you could asynchronously check each task as ot completes if it contains the correct result:
public async Task FindResultAsync(string[] urlList)
{
var downloadTasks = urlList.Select(url => DownloadStringAsync(url)).ToList();
while (downloadTasks.Count > 0)
{
await finishedTask = Task.WhenAny(downloadTasks)
if (finishedTask.Result == someValue)
{
return finishedTask.Result;
}
downloadTasks.Remove(finishedTask);
}
}
Upvotes: 0
Reputation: 19149
Parallel.For(0, 1000000, (i, loopState) =>
{
result[i] = Test(i);
if (result[i] == 0)
{
loopState.Stop();
return;
}
});
Upvotes: 4