I have a method which is run n times with different parameters, simplified:
foreach(var param in params)
ValueList.Add(SomeMethod(param));
I would like to do this:
foreach(var param in params)
TaskList.Add(SomeMethodAsync(param));
foreach(var task in TaskList)
ValueList.Add(await task);
async Task<SomeValue> SomeMethodAsync(SomeParam p)
{
//What to do here
//To make this call async
return SomeMethod(p);
}
How do I have to modify the current Method to apply the async functionality? The SomeMethod
does not use any framework-functions that provide async; it is fully synchronous.
To describe it in different words: I want n tasks of this method to run asynchronously/simultaneously using the new async/await keywords.
If your method does not return an asynchronous result then there's no point using async/await.
If you just want to run your methods in parallel, use Parallel.ForEach
Parallel.ForEach(params, param => ValueList.Add(SomeMethod(param)));
If SomeMethod does not use a task, or await any framework async calls then it will run on a single thread, regardless of whether you add async to the method definition.
Your best option in that case is to run SomeMethod in a task.
async Task<SomeValue> SomeMethodAsync(SomeParam p)
{
return await Task.Run<SomeValue>(() => SomeMethod(p));
}
Personally I think the Parallel.ForEach is clearer.
Just make it a function returning task.
Task<SomeValue> SomeMethodAsync(SomePAram p)
{
return Task<SomeValue>.Run(()=> SomeMethod());
}
SomeMethodAsync
is awaitable
now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.