RavenDB + async/await + UI thread + paired debugging = revealed mystery deadlock

In the previous post I talked about mystery deadlock I couldn’t find the reason for. After a quick paired debug session, I realized one thing…

One does not simply use async/await in UI thread


So, what was the reason? The culprit was… simply “wait” statement for couple of tasks.

1
2
3
4
5
6
7
exportSectionRegistar.Add("Indexes", () =>
{
Operations.ShowProgress("Begin reading indexes");
var indexCount = ImportIndexes(jsonReader).Result;
Operations.ShowProgress(string.Format("Done with reading indexes, total: {0}", indexCount));
return indexCount;
});

So, the line ImportIndexes(jsonReader).Result (and several other .Result invocations in the same method were the deadlock reason. The following little refactoring has solved the issue:

1
2
3
4
5
6
7
8
9
exportSectionRegistar.Add("Indexes", async () =>
{
Operations.ShowProgress("Begin reading indexes");
Operations.ShowProgress("Begin reading indexes");
var indexCount = await ImportIndexes(jsonReader);
Operations.ShowProgress(string.Format("Done with reading indexes, total: {0}", indexCount));
Operations.ShowProgress(string.Format("Done with reading indexes, total: {0}", indexCount));
return indexCount;
});

The moral of this facepalm causing story can be summed up as
assumptions-fuckup.jpg

I assumed that since I am running async/await method without waiting in UI thread, it won’t deadlock, since I am not waiting. And you can never know if the async method doesn’t do any waiting internally. Unless you properly look into it’s implementation that is.