The best practice for async/await is to use async “all the way down” (unless you really and truly don’t care about Method1 waiting for Method2 to complete).
It’s possible to mix Task.Wait (or similar constructs) with async code, but it’s a bad idea because it can lead to deadlocks.
The best thing here would be, as others have indicated, just make Method1 async too:
public async Task Method1() {
while (statement1) {
await Method2(i);
// ...
}
Note that you’ll have to make Method1 return a Task too because otherwise you can’t wait it:
public async Task Method2
This may be a case of the XY Problem though because there’s no reason for the code sample you provide to be async in the first place (or even a separate method, for that matter) – you can just do Thread.Sleep instead. Also, the “if” statement is pointless because, based on what you’ve shown us, you delay for 2 seconds either way. It would be helpful if you could show a more substantial code sample so we can get a better sense of what you’re trying to do so we can recommend whether async is even an appropriate solution here.
One final point: one of the purposes of async/await is to allow the calling thread to do other work while it’s waiting for a result – for example, if you want to download a file without “hanging” the UI. I’ve seen plenty of cases where people use async/await in a way that essentially obviates the purpose though. For example:
static void Main(string[] args) {
// This is a terrible thing to do but it's for illustration purposes
Task task = Method1();
task.Wait();
// Some other work
}
private static async Task Method1() {
await Method2();
// Some other work
}
private static async Task Method2() {
await Method3();
// Some other work
}
private static async Task Method3() {
await Task.Delay(1000);
}
This is a pretty dumb illustration, granted, but in this case the async/await is completely pointless because it’s just doing each action sequentially anyway.
2
solved How to call an async method from another method