Answer the question
In order to leave comments, you need to log in
How to properly implement async / await?
Goodnight. Please tell me how to correctly implement the following functionality in a WPF application:
There is a View with a DataGrid. The data for the DataGrid is taken from the ObservableCollection. I would like the ObservableCollection to be filled from the database with an asynchronous method. At the moment, the following is written, but, of course, it does not work. Tell me where the jamb, please:
View:
...
<dxg:GridControl ShowLoadingPanel="{Binding MerchantsLoading}" ItemsSource="{Binding Merchants}".../>
...
public MerchantViewModel {
MerchantsLoading = true;
Merchants = SQLite.GetMerchants().Result;
SQLite.GetMerchants().ContinueWith(task => MerchantsLoading = false);
}
public static async Task<ObservableCollectionCore<Merchant.Merchant>> GetMerchants()
{
SQLiteConnection SqlConnection = new SQLiteConnection(MerchantDB);
var Merchants = new ObservableCollectionCore<Merchant.Merchant>();
try
{
SqlConnection.Open();
SQLiteCommand myCommand = new SQLiteCommand("select * from merchant", SqlConnection);
DbDataReader myReader = await myCommand.ExecuteReaderAsync();
while (myReader.Read())
{
Merchants.Add(new Merchant.Merchant
{
ID = Convert.ToInt32(myReader["ID"]),
Name = Convert.ToString(myReader["Name"])
});
}
}
catch (Exception ex)
{
Messenger.Default.Send(new LogMessage { Message = "Ошибка в процедуре GetMerchants" });
Messenger.Default.Send(new LogMessage { Message = ex.ToString() });
}
finally
{
SqlConnection.Close();
}
return Merchants;
}
Answer the question
In order to leave comments, you need to log in
Merchants
in the ViewModel, implement it as a property with get and initialize it immediately in the constructor, or send a message to the DataGrid to update the dataset.
Not everything is asynchronous that ends with async.
In this case, not everything ends with async. Sometimes it's easier to create a long-running task (often).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question