Koen
Koen

Reputation: 2571

Close form after raising an event

I have a mainform that opens a StartForm at some point:

private void TestChosen(object sender, TestChosenEventArgs e)
{
    var frm = new TestStartForm(e.Test, StartTest);
    frm.ShowDialog();
}

On this StartForm I have a button to actually start the test.

public TestStartForm(Test test, StartTestHandler startTestHandler)
{
    InitializeComponent();
    _test = test;
    OnStartTest = startTestHandler;
}

public delegate void StartTestHandler(object sender, StartTestEventArgs e);
public event StartTestHandler OnStartTest;

public void InvokeOnStartTest(StartTestEventArgs e)
{
    StartTestHandler handler = OnStartTest;
    if (handler != null) handler(this, e);
}

private void btnStart_Click(object sender, EventArgs e)
{
    InvokeOnStartTest(new StartTestEventArgs(_test));
    Close();
}

The problem I'm facing is that the StartForm stays open untill the work of the StartTestHandler is completely done. In the StartTestHandler another form is opened with the actual test.

Is there a way to force the StartForm to close without waiting for the test to be finnished?

EDIT

As @cowboydan suggested I've used BeginInvoke to show the form.However, I had to do it for the StartForm as well as the actual TestForm before it worked properly.

private void TestChosen(object sender, TestChosenEventArgs e)
{
    BeginInvoke((Action)delegate
    {
        var frm = new TestStartForm(e.Test, StartTest);
        frm.ShowDialog();
    });

}

private void StartTest(object sender, StartTestEventArgs e)
{
    BeginInvoke((Action)delegate
    {
        var frm = new TestForm(e.Test);
        frm.ShowDialog();
    });
}

Upvotes: 0

Views: 74

Answers (1)

cowboydan
cowboydan

Reputation: 1102

You could use BeginInvoke which would launch StartForm in a separate thread from the ThreadPool. This is a fairly common practice.

Upvotes: 1

Related Questions