I try to become acquainted with async/await. So I try to write an C#/WPF program to query a database asynchronously without blocking my GUI.
I created an object implementing the INotifyPropertyChanged interface. This object offers a DataTable property and this should become changed by my async function. My GUI component has a binding to the DataTable property.
My object looks this way:
public class AsyncDataDemo : INotifyPropertyChanged
{
protected DataTable data = new DataTable();
public DataTable Data
{
get { return data; }
protected set
{
data = value;
doPropertyChanged("Data");
}
}
protected virtual void doPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChangedEventArgs Arguments = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, Arguments);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected async Task<DataTable> OpenQueryAsync(string ConnectionString, string Query)
{
OdbcConnection connection = new OdbcConnection(ConnectionString);
await connection.OpenAsync().ConfigureAwait(false);
OdbcCommand command = new OdbcCommand(Query, connection);
DbDataReader dataReader = await command.ExecuteReaderAsync().ConfigureAwait(false);
DataTable resultData = new DataTable();
resultData.Load(dataReader);
connection.Close();
return resultData;
}
public async void RunQueryAsync(string Query)
{
Data = await OpenQueryAsync("<ConectionString>", (Query as string)).ConfigureAwait(false);
}
}
And at a button click event I call:
private void Button_Click(object sender, RoutedEventArgs e)
{
data.RunQueryAsync("SELECT * FROM BigTable");
}
This works fine with one exception: the button click blocks my GUI until the data is loaded and I don't understand why.
Can somebody please explain my failure to me? I don't understand why the async function won't run asynchronously?
Regards