Helem Shoshi
Helem Shoshi

Reputation: 239

How do i tell a form not to be close if a backgroundworker is busy?

private void ScanClouds_FormClosing(object sender, FormClosingEventArgs e)
{
    backgroundWorker2.WorkerSupportsCancellation = true;
    if (backgroundWorker2.IsBusy)
    {
        backgroundWorker2.CancelAsync();
    }
    Terminate();
}

Beside calling the CancelAsync i also want to tell the form to not be close. And then in the completed event i'm closing the form:

private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled == true)
    {
        this.Close();
    }
}

The question is when i click to close the form how do i tell him not to be close and to close it in the completed event ?

Upvotes: 0

Views: 106

Answers (4)

isxaker
isxaker

Reputation: 9456

private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
   if (bgWorker.IsBusy)
        e.Cancel = true;
}

Upvotes: 2

Rahul Ranjan
Rahul Ranjan

Reputation: 1058

    private void ScanClouds_FormClosing(object sender, FormClosingEventArgs e)
{
    backgroundWorker2.WorkerSupportsCancellation = true;
    if (backgroundWorker2.IsBusy)
    {
        backgroundWorker2.CancelAsync();
e.Cancel = true;
    }
    Terminate();
}

you could also write e.Cancel=true in MyForm_FormClosing like above because it also internally calls OnFormClosing method of form.

Upvotes: 1

Remus Rusanu
Remus Rusanu

Reputation: 294267

Is a bad form to refuse to do the user action. Instead you should indicate, with visual feed-back and clues, that the form is not Close-able. For instance, set ControlBox to False while the background job is running.

You can also leave the form closeable, and abort the background task when the form is closed. Which, of course, require cooperation from the task (not all tasks are abortable).

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156978

You can override the OnFormClosing method, to prevent the form from closing. Set e.Cancel to true:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (backgroundWorker2.IsBusy)
    {
        e.Cancel = true;
        return;
    }

    base.OnFormClosing(e);
}

You could show a message box inside or do anything else to inform the user why you cancelled the closing.

Upvotes: 5

Related Questions