Kobi Hari
Kobi Hari

Reputation: 1248

async Task method that controls the scheduler it runs on

The typical way of writing an async Task method is as follows:

public async Task<int> LongCalculationAsync(int arg) 
{
     int res = doSomeLongCalculation();
     res += await CallSomeOtherTaskAsync();
     res ++;
     return res;
}

When written like this, the first part (before the await) is performed synchronously, and then another Task is created and started on perhaps another thread, which is then continued by a task that contains the last 2 lines and is run on the original context.

The problem is that the synchronous part is performed on whichever scheduler the caller runs on. But my problem is that I know that I want the task returned to run using a specific scheduler, even if the method is called from the UI thread.

Is there a way for the async method itself to decide on the context?

Upvotes: 1

Views: 672

Answers (1)

usr
usr

Reputation: 171178

Use Task.Factory.StartNew to push work to any scheduler you want. For the default thread-pool use Task.Run. It's quite easy:

await Task.Factory.StartNew(() => doSomeLongCalculation(), ...)

Upvotes: 1

Related Questions