长时间运行的进程冻结UI,如何使用线程更新? [英] Long running process freezing UI, how to update with threading?

查看:112
本文介绍了长时间运行的进程冻结UI,如何使用线程更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为长时间运行的过程编写了此示例代码,但是Windows Form会冻结直到过程完成.如何更改代码以使工作并行运行?

I've written this sample code for a long running process, but the Windows Form freezes until the process completes. How do I change the code so that the work runs in parallel?

var ui = TaskScheduler.FromCurrentSynchronizationContext();
Task t = Task.Factory.StartNew(delegate
{
    textBox1.Text = "Enter Thread";
    for (int i = 0; i < 20; i++)
    {
        //My Long Running Work
    }
    textBox1.Text = textBox1.Text + Environment.NewLine + "After Loop";
}, CancellationToken.None, TaskCreationOptions.None, ui);

推荐答案

您可以使用延续.我不记得确切的语法,但是有点像:

You can use a continuation. I don't remember the exact syntax but it's something like:

textBox1.Text = "Enter Thread"; //assuming here we're on the UI thread
Task t = Task.Factory.StartNew(delegate
{                
    for (int i = 0; i < 20; i++)
    {
        //My Long Running Work
    }
    return result;
})
.ContinueWith(ret => textBox1.Text = textBox1.Text + Environment.NewLine + result, 
    TaskScheduler.FromCurrentSynchronizationContext());

一种替代方法是:

Task t = Task.Factory.StartNew(delegate
{
    YourForm.Invoke((Action)(() => textBox1.Text = "Enter Thread");
    for (int i = 0; i < 20; i++)
    {
        //My Long Running Work
    }
    YourForm.Invoke((Action)(() => textBox1.Text = textBox1.Text + Environment.NewLine + result);}, 
        CancellationToken.None, TaskCreationOptions.None);

同样,我不记得确切的语法,但我的想法是要对与UI线程不同的线程执行长操作,但是要报告进度(包括完成)用户界面线程.

Again, I don't remember the exact syntax but the idea is that you want to perform the long operation on a thread different than the UI thread, but report progress (including completion) on the UI thread.

顺便说一句, BackGroundWorker 类将在这里也能很好地工作(我个人非常喜欢).

By the way, the BackGroundWorker class would work very well here, too (I personally like it very much).

这篇关于长时间运行的进程冻结UI,如何使用线程更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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