Task mytask = Task.Run(async () => ... What does mytask represent?

Task mytask = Task.Run(async () => 
        await semaphoreLock.WaitAsync(1000);

Open in new window

What does mytask actually represent?

Does it represent the Task created by Task.Run?

Or does it represent the Task returned by await?

Or is it a Task<Task>? (Apparently not as I can't specify that.)

Running the actual code I find sometimes mytask.Status = any of: Running, Ran to completion, Awaiting activation. Even though my infinite while loop is always still running.
Who is Participating?
Nitin SontakkeConnect With a Mentor DeveloperCommented:
Threading is one of the most complex topics in computing world. A lot of complexity is abstracted from us by providing above constructs.

There were 5 great videos by Jeffery Richter of WintellectNow explaining threading in details shared on Microsoft Virtual Academy for free.

Unfortunately they have now withdrawn 4 and just kept one. Link below:


And I found 3rd one on YouTube:


All should be available on WintellectNow of course.
käµfm³d 👽Connect With a Mentor Commented:
A task is similar to a promise (i.e. like in Javascript):  at some point you expect a value/result, but you don't need to block your code on that result until you actually need it. That's the purpose of await:  to block when you absolutely need the result before you can continue processing.

For your example, it seems a bit contrived, but based on what's visible, mytask is the Task returned by Task.Run. There is no value (i.e. it's a void lambda because you don't return anything), so it's simply a Task and not a Task<SomeType>. The result has to be some form of Task otherwise you can't await it later. If it were somehow void instead of Task, then it would be considered a fire-and-forget scenario.
deleydAuthor Commented:
Why does mytask.Status flip all over the place? I'd expect it to stay "Running" forever.
käµfm³d 👽Commented:
I'm afraid I do not understand the question.
deleydAuthor Commented:
I now think it's normal for an async Task to go between Awaiting Activation, Running, Completed, and back to Awaiting Activation. I think the only time an infinite loop Task can be said to have ended is if it enters the Canceled or Faulted state. Thank you everyone for your help!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.