即使使用线程后,UI也会冻结 [英] UI Freezing Even After Using Threads

查看:85
本文介绍了即使使用线程后,UI也会冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不冻结WPF UI的情况下,我需要执行一些崇高的数学计算.这是我为实现该目标而编写的代码.

I have some lofty mathematical calculations that I need to perform without freezing my WPF UI. Here's the code I wrote to achieve it.

new Thread(() =>
{
    ThreadPool.QueueUserWorkItem((state) =>
    {
        Dispatcher.Invoke(new Action(() =>
        {
            double x1_min = Convert.ToDouble(txt_x1_min.Text);
            double x1_max = Convert.ToDouble(txt_x1_max.Text);
            double x2_min = Convert.ToDouble(txt_x2_min.Text);
            double x2_max = Convert.ToDouble(txt_x2_max.Text);
            int iter = Convert.ToInt16(txtIterations.Text);
            //Data Defining and Computing
            obj.Run(x1_min, x1_max, x2_min, x2_max, iter);
            myDataGrid.ItemsSource = PSOLib.table.DefaultView;
            Minima.Text = string.Format("{0,0:0.000} ", PSOLib.min);
        }));
    });
}).Start();

我阅读了许多其他有关如何解冻它的主题,但是我对C#的线程模型真的不习惯.任何帮助将不胜感激. 谢谢.

I read many other topics on this how to unfreeze it, but I am really not well accustomed with C#'s threading model. Any help will be highly appreciated. Thanks.

推荐答案

将其放在 Dispatcher 上将仅在UI线程上运行代码,最终将冻结UI.因此,仅将UI stuf放在UI线程上,在第二线程上运行耗时的操作.

Putting it on Dispatcher will run your code on UI thread only which ultimately will freeze UI. So, only put UI stuf on UI thread and run time consuming operation on secondary thread.

double x1_min = Convert.ToDouble(txt_x1_min.Text);
double x1_max = Convert.ToDouble(txt_x1_max.Text);
double x2_min = Convert.ToDouble(txt_x2_min.Text);
double x2_max = Convert.ToDouble(txt_x2_max.Text);
int iter = Convert.ToInt16(txtIterations.Text);

ThreadPool.QueueUserWorkItem((state) =>
    {
        //Data Defining and Computing
        obj.Run(x1_min, x1_max, x2_min, x2_max, iter);
        Dispatcher.Invoke(new Action(() =>
        {
            myDataGrid.ItemsSource = PSOLib.table.DefaultView;
            Minima.Text = string.Format("{0,0:0.000} ", PSOLib.min);
        }));
    });

您还可以使用 BackgroundWorker 在另一个线程上运行耗时的操作,并在运行于UI线程上的BW的 RunWorkerCompleted 事件中进行UI更新代码(设置ItemsSource)本身.

Also you can use BackgroundWorker to run time consuming operation on another thread and UI updation code (setting ItemsSource) in RunWorkerCompleted event of BW which runs on UI thread itself.

这篇关于即使使用线程后,UI也会冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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