Below example shows how to create and use async methods in WPF application.
In below example, There are two ways to create void returning async method as well string returning
Async method.
you can copy and paste relevance code in any new WPF application and check it's functionality(mainly responsiveness). I tried to create long running operations and application responsiveness during long running operation.
.CS File
public partial class AsyncWithWPF : Window
{
string strGlobalVariable = "";
public AsyncWithWPF()
{
InitializeComponent();
}
private async void BtnAsyncReturnVoid1_Click(object sender, RoutedEventArgs e)
{
lblResult.Content = "";
lblResult.Content += " Starting.. ";
await LongRunningTaskReturnvoid1();
lblResult.Content += "Finished LongRunningTaskReturnvoid1() " + strGlobalVariable;
}
public Task LongRunningTaskReturnvoid1()
{
lblResult.Content += " inside LongRunningTaskReturnvoid1() ";
return Task.Factory.StartNew(() =>
{
Thread.Sleep(5000);
strGlobalVariable += " Async Task has finished ";
});
}
private void BtnAsyncReturnVoid2_Click(object sender, RoutedEventArgs e)
{
lblResult.Content = "";
lblResult.Content += " Starting.. ";
LongRunningTaskReturnvoid2();
lblResult.Content += "after LongRunningTaskReturnvoid2() call";
}
public async void LongRunningTaskReturnvoid2()
{
await Task.Factory.StartNew(() =>
{
Thread.Sleep(5000);
});
lblResult.Content += " finished LongRunningTaskReturnvoid2()";
}
private async void BtnAsyncReturn1_Click(object sender, RoutedEventArgs e)
{
string result = "";
lblResult.Content = "";
lblResult.Content += " Starting.. ";
try
{
result = await LongRunningTask();
}
catch(Exception ex)
{
MessageBox.Show("Handled");
}
lblResult.Content += result +" Finished LongRunningTaskvoid()";
}
public Task
{
lblResult.Content += " inside LongRunningTask() ";
return Task.Factory.StartNew(() =>
{
Thread.Sleep(5000); //throw new Exception("test");// uncomment to check exception handling.
return "Hello";
});
}
private void BtnTestResponsiveness_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello");
}
}
No comments:
Post a Comment