Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper SqlException and Unobserved exception

I have an issue with the following code when the T-SQL proc raises an error (SQLException)

    var result = await conn.QueryMultipleAsync("Inventory.uspLoadItems", new
    {
        dbId = obj.myId,
    },
    commandType: CommandType.StoredProcedure);
    var items = await result.ReadAsync();
    var specificItems = MyCustomMapper.MapTo<MyItem>((dynamic)items);

I'm using Dapper version 1.50.2.

The process is thrown into an Unobserved Exception.

I can follow the exception all the way up to the WebApi controller method. But when the controller method exists, another (spawn and unfinished) thread continue to execute at var items = await items.ReadAsync(); even if the WebApi session has been terminated (GC collected?). (Text deleted due to me misunderstanding information in Parallell Stack window. The exception failed at ReadAsync, not QueryMultipleAsync and hence didn't continue after the exception). Looks like a threading issue in Dapper, but I'm not sure.

UPDATE

I found the follwing link at Microsoft Connect that seems to be highly related to this topic. https://connect.microsoft.com/VisualStudio/feedback/details/2592987/sqldatareader-nextresultasync-causes-unobserved-task-exception-even-when-awaited

So, for anyone else who experiences this behavior. You'll have to wait for the next .NET update.

Not a Dapper problem, but if Dapper-contributers could find a temporary work-around, that would be nice :)

For now I change all my ReadAsync to Read (synchronous) to avoid this SqlDataReader bug.

like image 304
Frode Avatar asked Oct 18 '22 23:10

Frode


1 Answers

another (spawn and unfinished) thread continue to execute at var items = await items.ReadAsync();

Sounds like the function that all this code exists in executes asynchronously and is not awaited or otherwise synchronized with. The main request finishes while this function is still running (this is not a guess, it's proven by your observation that the code executes after the controller is done). Then, if this code crashes the exception is unobserved.

It would be an incorrect fix to ignore unobserved exceptions. I recommend doing that anyway, but the correct fix is to await the task that this code is part of.

Since it is your code that is still running it's not a framework bug. The bug you linked to might cause framework code to execute later and unobservedly, but it will not cause statements after your await to run (again).

like image 108
usr Avatar answered Oct 20 '22 21:10

usr