I am trying to understand something else about async/await and especially how the compiler knows to βsuspendβ the async and await method without creating additional threads.
As an example, suppose I have an async method like
DoSomeStuff(); await sqlConnection.OpenAsync(); DoSomeOtherStuff();
I know await sqlConnection.OpenAsync(); - this is where my method gets suspended, and the thread it calls returns to the thread pool, and as soon as the Task that monitors the connection is opened, then the available DoSomeOtherStuff() thread is available.
| DoSomeStuff() | "start" opening connection | ------------------------------------ | | ---------------------------------------------------------- | DoSomeOtherStuff() - |
Here where I am confused. I look at the source code of OpenAsync ( https://referencesource.microsoft.com/#System.Data/System/Data/Common/DBConnection.cs,e9166ee1c5d11996,references ) and it
public Task OpenAsync() { return OpenAsync(CancellationToken.None); } public virtual Task OpenAsync(CancellationToken cancellationToken) { TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>(); if (cancellationToken.IsCancellationRequested) { taskCompletionSource.SetCanceled(); } else { try { Open(); taskCompletionSource.SetResult(null); } catch (Exception e) { taskCompletionSource.SetException(e); } } return taskCompletionSource.Task; }
I assume that I will see a place where the compiler would know to "cut off" the stream, because the task began to communicate with an external resource, but I really do not see this, and in fact Open(); seems to mean that he is waiting synchronously. Can someone explain how this becomes modeless "true asynchronous" code?
source share