1

Trying to understand async/await in the sample below:

public static Task <string> job() { Console.WriteLine("start delay 1"); Task.Delay(2000); Console.WriteLine("sleep done 1"); Task<string> t = new Task<string>(()=> { Console.WriteLine("start delay 2"); Task.Delay(3000); Console.WriteLine("sleep done 2"); return "aaaa"; }) ; t.Start(); return t; } public async static void caller() { string s = await job(); Console.WriteLine("result is {0}", s); } public static void Main() { caller(); Console.WriteLine("done with caller"); Console.ReadLine(); } 

To get a more clear picture I would like to make task run a bit longer and I have added Task.Delay(). Both delays are taking no time and finish immediately. Why? How to make my task spend some time on simple job to make it last longer?

3
  • 2
    you have to await Task.Delay(ms) (Note you have to make job() async as @stuartd said for this to work) Commented Nov 7, 2017 at 11:09
  • job() should also be marked as async Commented Nov 7, 2017 at 11:10
  • have a look at the documentation and the code example there Commented Nov 7, 2017 at 11:17

2 Answers 2

2

Task.Delay creates a Task that delays for the time specified. You do spawn a Task that Delays for 2 Seconds but you never wait for it.

adding await to the call does fix this. (You have to mark the method async)

public static async Task <string> job() { ... await Task.Delay(2000); ... } 

You can read more about Asynchronous Programming here

Sign up to request clarification or add additional context in comments.

Comments

0

Task.Delay returns you a task that will complete in the given milliseconds you have provided. To hold execution of your code at this point (this is a massive simplification of what it does and you should definately do more learning on async/await in c#) you need to await the call to Task.Delay(2000) like this

await Task.Delay(2000); 

to use the await key word you need to mark your method signature as async like this

public static async Task<string> job() 

but I would highly recommend reading up on async and await

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.