I would like to know the reasoning behind the way the compiler choose the TaskScheduler when compiling using the async keyword.
My test method is called by SignalR (ASP.NET host, IIS8, websocket transport) on the OnConnectedAsync method.
protected override async Task OnConnectedAsync(IRequest request, string connectionId)
{
SendUpdates();
}
Starting a task on the Current synchronization context will result to an InvalidOperationException in System.Web.AspNetSynchronizationContext.OperationStarted()
An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked
<%@ Page Async="true" %>
.
Fine. With this SendUpdates definition, I get the above exception:
private async void SendUpdates()
{
Task.Run(async () =>
{
while (true)
{
await Task.Delay(1000);
await Connection.Broadcast("blabla");
}
});
}
But even more interesting is when I don't get the exception. The following works:
private void SendUpdates()
And the following works too
private async Task SendUpdates()
this last one works too, but it's essentially the same as the above example.
private Task SendUpdates()
{
return Task.Run(async () =>
{
while (true)
{
await Task.Delay(1000);
await Connection.Broadcast("blabla");
}
});
}
Do you know how the compiler choose which scheduler to use here?