Question

I've the following code, that from the first Stream is reading from a file, and doing some interpretations to the content and write them to the second file, I'm facing a problem that when I've a big file the GUI in WPF is sticking, I tried to put the reading and the writing actions in:

 Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                {
                    // Here
                });

This in the follwoing code:

using (StreamReader streamReader = new StreamReader(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
using (StreamWriter streamWriter = new StreamWriter(File.Open("Compressed_" + splitFilePath[splitFilePath.Length - 1], FileMode.Create, FileAccess.Write, FileShare.ReadWrite)))
{
    // Here are the interpretations of the code
    while ((dataSize = streamReader.ReadBlock(buffer, 0, BufferSize)) > 0)
    {
        streamWriter.Write(.....);
    }
}

Can anyone help me?? Thanks

Was it helpful?

Solution

You need to move the writing into a Background thread if you want to avoid blocking the UI.

This can be done via Task.Factory.StartNew:

var task = Task.Factory.StartNew( () =>
{
    using (StreamReader streamReader //.. Your code

});

This will, by default, cause this to run on a ThreadPool thread. If you need to update your user interface when this completes, you can use a continuation on the UI thread:

task.ContinueWith(t =>
{
    // Update UI here
}, TaskScheduler.FromCurrentSynchronizationContext());

OTHER TIPS

You need to understand, that even with BeginInvoke your code is executed on the SAME UI dispatcher thread, thus freezing your GUI. Try using tasks to run your logic in background.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top