How can I dispose a WinForm from a Non-Main Thread?
I have several threads running that are checked for .IsAlive
from within another thread in a loop. Then I try to dispose them after they all die but it is not working as I envisaged, how do I dispose correctly?
If you need to interact with WinForms from non-UI thread you can use Invoke method. Next example create a form, shows it and then call dispose on it
public class DisposeFormDemo
{
private class MyForm : Form
{
public MyForm() => Text = $"Main thread id = {Thread.CurrentThread.ManagedThreadId}";
}
public delegate void MyDelegate(Form form);
public static void Main()
{
var form = new MyForm();
Task.Run(async () => await Task.Delay(3000).ContinueWith(_ =>
{
MessageBox.Show($"Task thread id = {Thread.CurrentThread.ManagedThreadId}");
var myDelegate = new MyDelegate(f =>
{
MessageBox.Show($"Current thread id = {Thread.CurrentThread.ManagedThreadId}");
f.Dispose();
});
form.Invoke(myDelegate, form);
}));
form.ShowDialog();
}
}
As you can see delegate will be executed on UI thread