Goo*_*ber 17 c# multithreading
假设您有一个C#WinForms应用程序进行一些数据处理.您有一个方法可以从UI线程调用的数据库中检索数据.然后运行后台线程来执行此任务.您希望UI继续执行其操作,而不是被锁定和无响应.
如何让后台线程运行并进行处理,然后在返回结果时自动提醒UI线程?
Chr*_*isF 13
如果您不使用后台工作线程(无论出于何种原因),则必须从您的线程中触发由UI线程处理的事件.例如,我有这个代码,扫描我的mp3s,发现每个专辑的火灾和事件,然后是完成(或停止)的另一个事件:
public void Build()
{
FindAlbums(Root);
// Final update
if (Library_Finished != null)
{
Library_Finished(this, null);
}
}
private void FindAlbums(string root)
{
// Find all the albums
string[] folders = Directory.GetDirectories(root);
foreach (string folder in folders)
{
string[] files = Directory.GetFiles(folder, "*.mp3");
if (files.Length > 0)
{
// Add to library - use first file as being representative of the whole album
var info = new AlbumInfo(files[0]);
if (Library_AlbumAdded != null)
{
Library_AlbumAdded(this, new AlbumInfoEventArgs(info));
}
}
FindAlbums(folder);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在UI线程(这是WinForms代码):
private void Library_AlbumAdded(object sender, AlbumInfoEventArgs e)
{
if (dataGridView.InvokeRequired)
{
dataGridView.Invoke((MethodInvoker)delegate { AddToGrid(e.AlbumInfo); });
}
else
{
AddToGrid(e.AlbumInfo);
}
}
private void Library_Finished(object sender, EventArgs e)
{
if (dataGridView.InvokeRequired)
{
dataGridView.Invoke((MethodInvoker)delegate { FinalUpdate(); });
}
else
{
FinalUpdate();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我会建议您调查后台工作线程,因为它会为您完成大量的内务处理.但是,在RunWorkerCompleted更新UI时,将需要相同的处理代码.
有几种方法可以做到这一点,但最简单的方法是使用BackgroundWorker.
基本上它有两个代表,DoWork和WorkCompleted.DoWork在单独的线程上执行,WorkCompleted回调在UI线程上发生.
这里有更多信息:http: //msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx