Luk*_*e G 4 .net c# multithreading thread-safety winforms
有人可以帮我解决以下问题:
MainForm和LWriter有两个类.以下是来自LWriter的方法,除了写入文件之外,还向RichTextBox控件发送一些更新(通过mainForm.UpdateLog(text)).一切正常,但是,这个WriteOutput方法也做了一些广泛的处理,在计算过程中冻结了表单.
我认为WriteOutput应该封装在一个单独的线程中.有人可以帮我解释如何将WriteOutput(LWriter类)放在一个线程中,然后以安全的方式从mainFrom调用mainForm.UpdateLog()吗?
我是线程新手,因此非常感谢帮助.
public void WriteOutput(string output, Links[] links)
{
try {
using (StreamWriter sw = new StreamWriter(output)) {
for (int x= 1; x<links.Length;x++) {
...
sw.WriteLine( ... );
sw.Flush();
}
mainForm.UpdateLog(<text>);
}
} catch(Exception e) { ... }
}
Run Code Online (Sandbox Code Playgroud)
通常,您应该在a中运行这种耗时的操作BackgroundWorker.定义工作方法:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
// execute your WriteOutput method
}
Run Code Online (Sandbox Code Playgroud)
和set作为DoWork事件处理程序:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync(); // start the worker
Run Code Online (Sandbox Code Playgroud)
要从其他线程安全地更新UI,请使用以下Control.BeginInvoke方法:
mainForm.BeginInvoke(
() => { mainForm.UpdateLog(<text>); });
Run Code Online (Sandbox Code Playgroud)