Search code examples
c#arraysfilestream

Writing stream of inputted Byte Arrays to file over several minutes (C#)


I'm creating a GUI tool that extracts data from a microprocessor via Serial. I want to save the byte arrays that I am extracting into a .dat file in chunks as they are extracted. I tried using a filestream, but the process takes several minutes so the GUI freezes while the filestream is open.

How can I save to a filestream multiple times over a long period without freezing the GUI?

Should I just store the extracted byte arrays and then write to the file after? I was going to do this but it would require a byte array with over 8 million elements so I thought it wasn't the best idea.


Solution

  • If you are using the .NET Framework 4 or later you can use tasks. Then you can also make use of the ContinueWith method to update the UI on completion:

    Task writeTask = Task.Factory.StartNew(() =>
    {
        // Write to file
    }).ContinueWith(previousTask =>
    {
        // Update the UI
    });
    

    If you are using an older version of the .NET Framework you can either use the Task Parallel Library or explicitly use a thread.

    You can do this by either creating a new one or using the thread pool:

    Thread thread = new Thread(() =>
    {
        // Write to file
    });
    // Make the thread a background thread if you want it to be aborted
    // when the main thread is stopped, i.e. the application is closed:
    thread.IsBackground = true;
    thread.Start();
    

    -

    ThreadPool.QueueUserWorkItem(state =>
    {
        // Write to file
    });
    

    IMHO I prefer using tasks over threads and the thread pool over creating new threads. However, you have to keep in mind that using the thread pool does not guarantee to execute directly, but when a thread pool thread becomes available.