c# - 如何使用 Control.Dispatcher.BeginInvoke 修改 GUI

标签 c#

我需要从一个需要很长时间才能完成的方法内部修改 GUI。当我阅读其他帖子时, 解决方案之一是使用 Control.Dispatcher.BeginInvoke 在工作线程内设置 GUI。 但是,我不知道如何在这里执行此操作。

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Task.Factory.StartNew( () =>
        {
            ProcessFilesThree();
        });
    }

    private void ProcessFilesThree()
    {
        string[] files = Directory.GetFiles(@"C:\temp\In", "*.jpg", SearchOption.AllDirectories);

        Parallel.ForEach(files, (currentFile) =>
        {
            string filename = Path.GetFileName(currentFile);

                    // the following assignment is illegal
            this.Text = string.Format("Processing {0} on thread {1}", filename,
                                        Thread.CurrentThread.ManagedThreadId); 
        });

        this.Text = "All done!"; // <- this assignment is illegal
    }
}

最佳答案

尝试以下操作:

 msg = string.Format("Processing {0} on thread {1}", filename,
            Thread.CurrentThread.ManagedThreadId);
 this.BeginInvoke( (Action) delegate ()
    {
        this.Text = msg;
    });

关于c# - 如何使用 Control.Dispatcher.BeginInvoke 修改 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6170427/

相关文章:

c# - 只返回特定属性

c# - ASP.NET中长轮询结合WCF服务监控的例子?

c# - 如何在自动建议框中使用向下箭头键?

c# - 使用 Thread.Sleep 时如何更新 UI

c# - 为什么在 EPPLUS 的 excel 公式中 = 符号后有 @ 符号?

c# - 以编程方式将应用程序添加到所有配置文件 Windows 防火墙 (Vista+)

c# - 使用列表项内容作为字符串名称

c# - Visio 和 C# 编程

c# - 跨域不适用于 signalr 2.0

c# - Enum.HasFlag 未按预期工作