S
S
Smilley2016-08-04 02:00:32
Programming
Smilley, 2016-08-04 02:00:32

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}".../>
...

viewmodel:
public MerchantViewModel {
            MerchantsLoading = true;
            Merchants = SQLite.GetMerchants().Result;
            SQLite.GetMerchants().ContinueWith(task => MerchantsLoading = false);
}

GetMerchants:
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

2 answer(s)
R
Rou1997, 2016-08-04
@Rou1997

Merchantsin 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.

#
#algooptimize #bottize, 2016-08-04
@user004

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 question

Ask a Question

731 491 924 answers to any question