为什么我的GUI冻结

为什么我的GUI冻结

本文介绍了为什么我的GUI冻结?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是TPL世界的新人,我做了这个代码:

I'm new in TPL world, and I did that code:

    var myItems = myWpfDataGrid.SelectedItems;

    this.Dispatcher.BeginInvoke(new Action(() =>
    {
        var scheduler = new LimitedConcurrencyLevelTaskScheduler(5);
        TaskFactory factory = new TaskFactory(scheduler);

        foreach (MyItem item in myItems)
        {
            Task myTask = factory.StartNew(() =>

            DoLoooongWork(item)

                ).ContinueWith((t) =>
                {
                    Debug.WriteLine(t.Exception.Message);
                    if (t.Exception.InnerException != null)
                    {
                        Debug.WriteLine(t.Exception.InnerException.Message);
                    }
                },
                TaskContinuationOptions.OnlyOnFaulted);
        }
    }), null);

只有一个对gui的访问是 var myItems = myWpfDataGrid.SelectedItems;
,它是只读的!功能DoLoooongWork()访问串行端口等。它是一个分离的SDK函数,不访问GUI。我知道Dispatcher.BeginInvoke有点多余,但我不知道我能做什么,或者我做错了什么。这个代码的唯一原因是在执行DoLoooongWork()时释放GUI,但GUI被冻结!

The only one access to gui is "var myItems = myWpfDataGrid.SelectedItems;" and it is read only! The function "DoLoooongWork()" does access to serial ports, etc. It's a separated SDK function that doesn't access the GUI. I know that "Dispatcher.BeginInvoke" is a bit redundant, but I don't know what I can do, or what I'm doing wrong. The only reason to this code is to free the GUI while "DoLoooongWork()" executes, but the GUI is frozen!

该代码有什么问题?

编辑

感谢@Euphoric帮助,我发现类似于该帖子的问题:

Thanks to @Euphoric help, I discovered the problem that is similar to that post:COM Interop hang freezes entire COM system. How to cancel COM call

推荐答案

我有一个预感,串口工作的东西会尝试使用应用程序的事件循环来做它的工作。所以它实际上绕过整个调度程序和线程系统并阻止应用程序。我没有在这个领域的经验,所以我不知道如何解决它,但这是不同的问题。

I had a hunch that something working with serial port would try to use application's event loop to do it's work. So it actually bypasses the whole dispatcher and thread system and blocks the application. I'm not experienced in this field so I don't know how to solve it, but this is different question.

这篇关于为什么我的GUI冻结?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:01