Control Freak
Control Freak

Reputation: 13233

Using async to run multiple methods

Lets say I have this code:

public async void Init(){
    init1();
    init2();
    init3();     
}

First question is are they running asynchronously or not? The methods themselves are public void not async.

Second question is how do I make sure they're running async and to know when they're finished? Like this..

public async void Init(){
    init1();
    init2();
    init3();     
    await ... all finished
}

Third, when I call Init() elsewhere, can it not be wrapped by an async method? Like this code below, or does it have to be async?

public async void Init(){
    init1();
    init2();
    init3();   
}

public void doIt(){
  Init();
}

Upvotes: 2

Views: 9938

Answers (2)

Usman Khalid
Usman Khalid

Reputation: 170

Also One Thing you can do await on each on the methods to get the required result of each methods.

var task1 = await init1Async();
var task2 = await  init2Async();
var task3 = await init3Async();

Upvotes: 0

Stephen Cleary
Stephen Cleary

Reputation: 456507

I have an async intro that should help.

First question is are they running asynchronously or not?

No, and you didn't really need to ask this on Stack Overflow because the compiler itself will give you a warning that explicitly states your method will run synchronously.

Second question is how do I make sure they're running async and to know when they're finished?

First, your methods need to be properly asynchronous:

async Task init1Async();
async Task init2Async();
async Task init3Async();

Then you can make the caller invoke them concurrently and then asynchronously wait for them all to complete:

async Task InitAsync() {
  var task1 = init1Async();
  var task2 = init2Async();
  var task3 = init3Async();
  await Task.WhenAll(task1, task2, task3);
}

Third, when I call Init() elsewhere, can it not be wrapped by an async method?

Once your InitAsync method is properly defined as returning a Task, it can be naturally consumed using await:

async Task doItAsync() {
  await InitAsync();
}

Note that this does require the caller to be async.

Also recommended reading: my Best Practices for Asynchronous Code MSDN article, particularly the sections on "avoid async void" and "async all the way".

Upvotes: 9

Related Questions