A simple approach would be to wrap the DB operations in a Task:
public async Task DoDbOperationsAsync()
{
await Task.Run(async () =>
{
// Your DB operations goes here
// Any work on the UI should go on the UI thread
// WPF
await Application.Current.Dispatcher.InvokeAsync(() => {
// UI updates
});
// WinForms
// To do work on the UI thread we need to call invoke on a control
// created on the UI thread..
// "this" is the Form instance
this.Invoke(new Action(() =>
{
button1.Text = "Done";
}));
});
}
As mentioned in the comments, if this method is invoked from the UI, you can simply do your async operations in the Task, and when await
resumes, there is no need to look for a Dispatcher, since await
in this case is resuming on the UI thread. An example of that is given here:
public async void OnButtonClick_DoDbOperationsAsync()
{
await Task.Run(() =>
{
// Your DB operations goes here
});
// You are now back at the UI thread and can update the UI..
}