Question

I recently encountered this very strange problem. Initially I have this block of code

public async Task<string> Fetch(string module, string input)
{
    if (module != this._moduleName)
    {
        return null;
    }
    try
    {
        var db = new SQLiteAsyncConnection(_dbPath);
        ResponsePage storedResponse = new ResponsePage();

        Action<SQLiteConnection> trans = connect =>
            {
                storedResponse = connect.Get<ResponsePage>(input);
            };
        await db.RunInTransactionAsync(trans);
        string storedResponseString = storedResponse.Response;
        return storedResponseString;
    }
    catch (Exception e)
    {
        return null;
    }
}

However control will never be handed back to my code after the transaction finishes running. I traced the program and it seems that after the lock is release, the flow of program stops. Then I switched to using the GetAsync method from SQLiteAsyncConnection class. Basically it did the same thing so I was still blocked at await. Then I removed the async calls and used the synchronous api like below:

public async Task<string> Fetch(string module, string input)
{
    if (module != this._moduleName)
    {
        return null;
    }
    try
    {
        var db = new SQLiteConnection(_dbPath);
        ResponsePage storedResponse = new ResponsePage();
        lock (_dbLock)
        {
            storedResponse = db.Get<ResponsePage>(input);
        }
        string storedResponseString = storedResponse.Response;
        return storedResponseString;
    }
    catch (Exception e)
    {
        return null;
    }
}

Only then can the logic flows back to my code. However I can't figure out why is this so. Another problem is that for this kind of simple query is there any gain in terms of query time if I use aysnc api instead of sync api? If not I'll stick to the sync version then.

Was it helpful?

Solution

You are most likely calling Result (or Wait) further up the call stack from Fetch. This will cause a deadlock, as I explain on my blog and in a recent MSDN article.

For your second question, there is some overhead from async, so for extremely fast asynchronous operations, the synchronous version will be faster. There is no way to tell whether this is the case in your code unless you do profiling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top