Search code examples
c#backgroundworkerusingstreamreader

Is it good practice to pass a StreamReader to a background worker DoWork method?


I am creating a GUI in Visual C# and I'm implementing a feature where the user can open a file and I read lines from that file. I have code that creates a StreamReader from an OpenFileDialog in the main GUI thread and then passes the StreamReader to a BackgroundWorker.

StreamReader streamRdr = new StreamReader(dialog.OpenFile());
worker.RunWorkerAsync(streamRdr);

Is this good practice? I'm passing the StreamReader object to the background thread because I don't want the BackgroundWorker to handle the OpenFileDialog code.

In the BackgroundWorker DoWork method I use the StreamReader like this

using (StreamReader tempRdr = (StreamReader)e.Argument)
{
    // read from StreamReader...
    return;
}

My second question is will the StreamReader be closed properly even though it was created in the main GUI thread? And also do I have to explicitly call StreamReader.Close()? Or will the using statement take care of that on return from the DoWork method?


Solution

  • Since you're just closing the streamreader at the end of the call anyway, I'd recommend passing the filename to your DoWork method rather than the streamreader. Though I don't see any explicit problems with your code, it's generally "good practice" to open and close things from the same thread (and preferably from the same function if possible). Since the filename is just a string, you don't have to worry at all about multithreaded access.

    Note the useful methods System.IO.File.ReadAllBytes, ReadAllText, and ReadAllLines that may make your life easier if you pass the filename to the DoWork method.