WPF穿线抓斗

时间:2011-06-07 13:07:25

标签: wpf multithreading image backgroundworker threadpool

我开发了一个有趣的WPF控件,目前正在减慢我的整个应用程序:)在我的自定义控件上,我有一个图像控件,每次发生后端事件时我都需要更新。这个后端事件每秒发射两次(非常快)。当事件触发时我需要从第三方控件中拉出一个Bitmap对象,转换为BitmapSource对象然后将其绑定到我的Image控件。每次我的事件被触发时,我都在ThreadPool中排队一个新的工作项。然后该项将获取位图并在后台工作程序对象中进行转换。每次事件触发时都会执行此操作。我正在使用调度程序更新我的图像控件源与BeginInvoke但我仍然得到一个无响应的应用程序。请让我知道我可以做些什么来使这个过程更好地执行,并帮助我的应用程序更具响应性:

以下是我的活动中的代码:

void inSight_ResultsChanged(object sender, EventArgs e)
        {

            ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessEvent), ((InSightViewer)this.DataContext).CvsDisplay);
        }

以下是委托代码:

void ProcessEvent(object display)
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.RunWorkerAsync(display);

        }

以下是我的后台工作者DoWork事件中的代码:

void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            3rdPartyControl displayControl = new 3rdPartyControl();

            displayControl.ImageHost = (ImgHost)e.Argument;


            Bitmap b = displayControl.GetBitmap();

            var mBitmap = b.GetHbitmap();
            BitmapSource bs;

            try
            {
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                           mBitmap,
                           IntPtr.Zero,
                           Int32Rect.Empty,
                           BitmapSizeOptions.FromEmptyOptions());

                bs.Freeze();
            }
            catch (System.Exception ex) { throw ex; }
            finally
            {
                DeleteObject(mBitmap);
            }

            e.Result = bs;
        }

以下是RunWorkerCompleted事件中的代码:

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle, (ThreadStart)delegate()
        {
            this.imgSource.Source = (BitmapSource)e.Result;
        });
}

1 个答案:

答案 0 :(得分:0)

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
        Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle, (ThreadStart)delegate()
        {
            this.imgSource.Source = (BitmapSource)e.Result;
        });
}

System.Windows.Threading.DispatcherPriority。 ApplicationIdle 表示在应用程序空闲时处理操作。

如果应用程序总是很忙而且从不闲置怎么办?请求将排队,应用程序将变慢。

但是我没有对此进行测试,因为我没有您应用的源代码。