V
V
Vladislav Dyuzhev2020-04-26 15:01:13
WPF
Vladislav Dyuzhev, 2020-04-26 15:01:13

What is the correct way to pass a WriteableBitmap object from one thread to another (BackgroundWorker)?

Hello, I'm writing a small WPF application that does some processing on an image and then displays it in a MainImage. It does this for a long time, so I decided to shove all the processing code into a separate function and use a BackgroundWorker (for convenient progress display).
Simplified, everything looks like this:

This code is executed after getting the path to the image:

private void SelectImage ()
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += worker_DoWork;
            worker.ProgressChanged += worker_ProgressChanged;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.RunWorkerAsync(path); // path - строка (путь к изображению)
        }


Image processing function:
private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            writableBitmap = new WriteableBitmap(new BitmapImage(new Uri((string)e.Argument))));
            //  Код обработки изображения ...
            e.Result = writeableBitmap.Clone();
        }


Code after processing:
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MainImage.Source = (WriteableBitmap)e.Result;
        }


The program runs without exception, but the image doesn't show up in the end, although when the code is executed on the main thread, everything works fine. I just recently started learning WPF and C# in general, so I'm not even sure what could be the reason.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
d-stream, 2020-04-27
@d-stream

https://docs.microsoft.com/en-us/dotnet/api/system...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question