I'm playing a bit with async await, and tried to replace a backgroundworker with it.
The following code however will throw a exception when i close the form, and the task is still running: Cannot access a disposed object. Object name: 'TextBox'
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
await this.UpdateTextbox();
}
private async Task UpdateTextbox()
{
for (int i = 0; i < 1000; i++)
{
//TaskDelay only simalates any async work
await Task.Delay(50);
textBox1.AppendText(string.Format("{0}{1}", i, Environment.NewLine));
}
}
I do understand that because of the short delay when writing to the textbox, it'll try to write when the textbox is already disposed.
If i just remove the async/await from the click event, there is no error anymore when closing the form.
private void button1_Click(object sender, EventArgs e)
{
this.UpdateTextbox();
}
Question: Is it correct just to remove await async from the click eventhandler, and what is the difference there?
Are there situations when a forms eventhandler should be async?