Skip to main content
 首页 » 编程设计

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

2024年02月23日14lovecherry

我需要从一个需要很长时间才能完成的方法内部修改 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; 
    });