问题
In my UWP app, I've got an async method (event handler) that calls another async method, which attempts to insert a record into a database.
I'm getting an exception in the insertion attempt, and am trying to sherlock why it's happening. So I put a breakpoint in the InsertMapRecord() method, on the first "using" line:
using (SqliteConnection conn = new SqliteConnection(connStr))
When I reach that breakpoint, I hit F10, but instead of taking me to the next line in the Insert method, it takes me to this line in btnCre8NewMap_Click(), the event handler (which has already been hit, you would think, for the previous line to have been reached):
InsertMapRecord(mapName, mapNotes, defaultZoomLevel);
I then hit F11, in an attempt to return to the InsertMapRecord() method, but instead I end up at App.g.i.cs, on this line:
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
...with "global::System.Diagnostics.Debugger.Break()" highlighted, and then with this exception message:
The full methods are below
private async void btnCre8NewMap_Click(object sender, RoutedEventArgs e)
{
try
{
string mapName = string.Empty;
string mapNotes = string.Empty;
int defaultZoomLevel = 1;
ClearLocations();
// Popul8 the cmbx
for (int i = 1; i < 20; i++)
{
cmbxCre8MapZoomLevels.Items.Add(i.ToString());
}
ContentDialogResult result = await cntDlgCre8Map.ShowAsync();
if (result == ContentDialogResult.Primary)
{
mapName = txtbxMapName.Text;
mapNotes = txtbxMapNotes.Text;
defaultZoomLevel = cmbxCre8MapZoomLevels.SelectedIndex + 1;
InsertMapRecord(mapName, mapNotes, defaultZoomLevel);
}
// else do nothing (don't save)
}
catch (Exception ex)
{
MessageDialog exceptionMsgDlg = new MessageDialog(ex.Message, "btnCre8NewMap_Click");
await exceptionMsgDlg.ShowAsync();
}
}
private async void InsertMapRecord(string mapName, string mapNotes, int preferredZoomLevel)
{
path = folder.Path;
connStr = string.Format(connStrBase, path);
try
{
using (SqliteConnection conn = new SqliteConnection(connStr))
{
String query = "INSERT INTO dbo.CartographerMain " +
"(MapName, MapNotes, PreferredZoomLevel) " +
"VALUES (@MapName, @MapNotes, @PreferredZoomLevel)";
using (SqliteCommand cmd = new SqliteCommand(query, conn))
{
cmd.Parameters.AddWithValue("@MapName", mapName);
cmd.Parameters.AddWithValue("@MapNotes", mapNotes);
cmd.Parameters.AddWithValue("@PreferredZoomLevel", preferredZoomLevel);
conn.Open();
int result = cmd.ExecuteNonQuery();
if (result < 0)
{
MessageDialog dialog = new MessageDialog("Error inserting data into CartographerMain");
await dialog.ShowAsync();
}
}
}
}
catch (SqliteException sqlex)
{
MessageDialog dialog = new MessageDialog(sqlex.Message, "InsertMapRecord");
await dialog.ShowAsync();
}
}
回答1:
The InsertMapRecord
method should return a Task
that can be awaited by the caller. Also, it shouldn't block when you open a connection to the database or execute the query:
private async Task InsertMapRecord(string mapName, string mapNotes, int preferredZoomLevel)
{
path = folder.Path;
connStr = string.Format(connStrBase, path);
try
{
using (SqliteConnection conn = new SqliteConnection(connStr))
{
String query = "INSERT INTO dbo.CartographerMain " +
"(MapName, MapNotes, PreferredZoomLevel) " +
"VALUES (@MapName, @MapNotes, @PreferredZoomLevel)";
using (SqliteCommand cmd = new SqliteCommand(query, conn))
{
cmd.Parameters.AddWithValue("@MapName", mapName);
cmd.Parameters.AddWithValue("@MapNotes", mapNotes);
cmd.Parameters.AddWithValue("@PreferredZoomLevel", preferredZoomLevel);
await conn.OpenAsync();
int result = await cmd.ExecuteNonQueryAsync();
if (result < 0)
{
MessageDialog dialog = new MessageDialog("Error inserting data into CartographerMain");
await dialog.ShowAsync();
}
}
}
}
catch (SqliteException sqlex)
{
MessageDialog dialog = new MessageDialog(sqlex.Message, "InsertMapRecord");
await dialog.ShowAsync();
}
}
async void
methods should be avoided (except for event handlers).
In your event handler you should then await the InsertMapRecord
method and any other async method:
if (result == ContentDialogResult.Primary)
{
mapName = txtbxMapName.Text;
mapNotes = txtbxMapNotes.Text;
defaultZoomLevel = cmbxCre8MapZoomLevels.SelectedIndex + 1;
await InsertMapRecord(mapName, mapNotes, defaultZoomLevel);
}
If you do this, you should be able to catch any exception and investigate further.
回答2:
Since event handlers return void
and the async/await pattern requires the method to return a Task
of some kind, the application is arbitrarily moving past your event handler.
The case is likely that, while the application waits for your interaction on the breakpoint, the thread yields. This allows the application to continue running, and since your event handler returns void
it doesn't have an await context to continue from.
See this answer on help with using async/await in event handlers: https://stackoverflow.com/a/27763068/7241762
And also checkout Microsoft's crash course on async/await: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/
To try and be more clear, these symptoms appear to indicate that your lack of await
on calls to async
methods (see the call to InsertMapRecord
), and the lack of Task
or Task<T>
return types on your async
methods are causing synchronization problems in the application. Event handlers in C# need to return void
, but there are workarounds like the one explained in the linked answer from a different question.
来源:https://stackoverflow.com/questions/65293298/how-can-i-prevent-one-async-method-from-monopolizing-another