views:

39

answers:

1

Hello,

I'm developing C# .NET windows Forms application. In which I've a main window and few other window form classes (which are used as dialogs). I've a computationally intensive task(takes 3-4min). When user selects this task from the menu, a new dialog (window) pops up and takes parameters required from the user and it has a progress bar which shows the progress of the task. I'm using BackgroundWorker in this dialog to perform the computation and report progress. This BackgroundWorker also writes all the intermediate values to a log file named status.log.

Problem is, when the user closes this dialog the log file needs to be closed. I guess BackgroundWorker associated with this object will also get destroyed. So, I've wrote even handler for FormClosed event of this dialog and closing the file in that. But it seems that BackgroundWorker isn't killed by then. I mean, BackgroundWorker is now throwing an Exception that file is closed & cannot write to a stream that is closed.

How to handle this situation? When should I close the filestream? When does BackgroundWorker thread get killed?

+1  A: 

Background worker threads do not get killed: they are returned to the threadpool.

Handle the RunWorkerCompleted event.

UPDATE: in response to your comment: In the close event of the Form, signal the background worker to cancel. See accepted answer to .NET: How to wait for a BackgroundWorker to cancel?

Mitch Wheat
I'm not talking about the situation where the task is completed. I'm already handling the event `RunWorkerCompleted`. I'm talking about situation when user (abruptly) closes the dialog in the middle of computation. Then also I need to close the file because If I start the dialog again, it complains that file is used by some other process.
claws