Home > Mobile >  C# Form closes and reopens, throws "cannot access a disposed object"
C# Form closes and reopens, throws "cannot access a disposed object"

Time:09-17

I have a button that starts a new form, and this button runs a async task. When I close the form and click the button again, it throws "cannot access a disposed object". Here is the pseudocode.

private async void button_click(object sender, EventArgs e)
{
    await work();
}

private async Task work()
{
    form.show();
    while(true)
    {
        await Task.Run(async () => sendData(data1, data2)); // this just sends some data to the new form
        await Task.Delay(1000);
    }
}

The second form simply displays the data sent. I do not need this to run in background when the form is closed. I am new to async method, so not sure how to get around this problem..

CodePudding user response:

When you close the form it gets dispose. You need to initialize a new form in your worker.

private async Task work()
{
    Form form = new Form();
    form.Show()
    while(true)
    {
    await Task.Run(async () => sendData(data1, data2)); // this just sends some data to the new form
    await Task.Delay(1000);
    }
}
  • Related