Manuel Schweigert
Manuel Schweigert

Reputation: 4974

C# Async without framework functions

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.

Upvotes: 2

Views: 159

Answers (2)

Cameron MacFarland
Cameron MacFarland

Reputation: 71856

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.

Upvotes: 2

L.B
L.B

Reputation: 116098

Just make it a function returning task.

Task<SomeValue> SomeMethodAsync(SomePAram p)
{
    return Task<SomeValue>.Run(()=> SomeMethod());
}

SomeMethodAsync is awaitable now.

Upvotes: 1

Related Questions