在WPF多线程使用C#(与后台工作) [英] Multi threading in WPF using C# (with background worker)

查看:359
本文介绍了在WPF多线程使用C#(与后台工作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写代码来保存这是由应用程序生成的图像。图像的大小约为32-35 MB。在保存图像到 BMB 文件,它走的是一条很长一段时间,围绕3-5秒。为此,我使用了一个后台工作,但运行的后台工作时,它显示了一个这样的错误......,因为它是在不同的线程创建的无法访问对象。

I have written code to save an image which is generated by the application. The size of the image is around 32-35 MB. While saving the image to a BMB file, it is taking a long time, around 3-5 secs. For this purpose, I have used a background worker but when running the background worker, it shows an error like..."can't access the object as it is created on different thread".

以下是代码:

 private void btnSaveDesign_Click(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
        sfd.Title = "Save design as...";
        sfd.Filter = "BMP|*.bmp";
        if (sfd.ShowDialog() == true)
        {
            ww = new winWait();
            ww.Show();
            System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker();
            bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            fName = sfd.FileName;
            cache = new CachedBitmap((BitmapSource)imgOut.Source, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

            bw.RunWorkerAsync();


        }  
    }

    void bw_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        ww.Close();
    }

    void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        BmpBitmapEncoder encoder = new BmpBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(cache)); //here... it says cant access...
        using (FileStream file = File.OpenWrite(fName))
        {
            encoder.Save(file);
        }
    }



我已经声明缓存作为一个全局对象。 (一个类似的伎俩工作时,我在Windows窗体与VB.NET是编程。)

I have declared "cache" as a global object. (A similar trick worked when I was programming in Windows Forms with VB.NET.)

WW 是等待我想在正在执行的进动将要显示的窗口。

ww is the wait window that I want to be displayed while the precess is being executed.

如何做到这一点?有没有在WPF多线程任何其他简单的方法?

How to do this? Is there any other simple method for multi threading in WPF?

推荐答案

在创建WPF对象,他们被分配到一个调度对象。这比不允许创建线程访问对象以外的任何线程。这可以通过调用冷冻方法冻结对象来规避。你会需要调用冻结你的BitmapSource对象。一旦你冻结你的对象就变成无法修改

When WPF objects are created they are assigned to a Dispatcher object. This disallows any threads other than the creating thread to access the object. This can be circumvented by freezing the object by calling the freeze method. You would need to call Freeze on your bitmapsource object. Once you have frozen your object it becomes uneditable

这篇关于在WPF多线程使用C#(与后台工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆