While designing a web API I came to SignalR which seems to fit my demands having a persistent connection to the server which holds a state for the current client.
My problem is the "async - only" api.
I rarely use TPL and I used to synchronize async calls with .Wait() or .Result() which (I learned is bad practice) in a separate thread by message pumping and this worked for me so far.
I understood when using await, my code below can be executed on the same thread context as the ...Async() function which can cause a deadlock when using .Wait() or .Result when the same thread context is used.
But find the code below:
AutoResetEvent are = new AutoResetEvent(false);
private void Invoke()
{
Thread s = new Thread(() =>
{
Task t = hubConnection.InvokeAsync("Sum", 5, 7);
t.Wait();
are.Set();
});
s.Start();
are.WaitOne();
Invoke() is called from UI thread. This call starts a complete new thread in which the async call is performed. But also here, when calling .Wait() everything is blocked.
If we replace the SignalR call
Task t = hubConnection.InvokeAsync();
t.Wait();
by
Task t = Task.Delay(5000);
t.Wait();
it works as expected.
Can someone solve this puzzle for me? And how can I make real synchronous calls to that SignalR api
[Edit]
Meanwhile tried include async / await
See this code
AutoResetEvent are = new AutoResetEvent(false);
private void Invoke()
{
Thread s = new Thread(async () =>
{
await hubConnection.InvokeAsync("Sum", 5, 7);
are.Set();
});
s.Start();
are.WaitOne();
}
This case also causes deadlock. How is this still possible? I think there must be a bug.