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

Given:
Task mytask = Task.Run(async () => 
{
    while(true)
    {
        ...
        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.
deleydAsked:
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:

https://mva.microsoft.com/en-US/training-courses/advanced-net-threading-part-1-thread-fundamentals-16656?l=zAsojditC_6606218965

And I found 3rd one on YouTube:

https://www.youtube.com/watch?v=CYowfMeSg_k&list=PL9XzOCngAkqudQyRcJnb3bwjx8m6C_Gaw&index=9&t=0s

All should be available on WintellectNow of course.
0
 
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.
0
 
deleydAuthor Commented:
Why does mytask.Status flip all over the place? I'd expect it to stay "Running" forever.
0
 
käµfm³d 👽Commented:
I'm afraid I do not understand the question.
0
 
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!
0
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.