[英]Multithreaded Applications
我一直在阅读有关MSDN的文章,但我的思绪已经死了(这通常发生在我阅读MSDN时(没有攻击MSDN,但你的文章有时会让我感到困惑。)),而我正在尝试做一些“背景工作”在我的应用程序中,但不知道如何。 这只是一种方法。 但应用程序挂起,我必须等待1到3分钟才能变成......没变?
是否有任何简单的例子可以在网上铺设,我可以看看/玩耍?
谢谢你们
Jon Skeet写了一篇关于.NET中多线程的精彩介绍 ,你可能会读到。 它还包括WinForms中的线程 。 它可能属于以下几行:
public partial class Form1 : Form
{
private BackgroundWorker _worker;
public Form1()
{
InitializeComponent();
_worker = new BackgroundWorker();
_worker.DoWork += (sender, e) =>
{
// do some work here and calculate a result
e.Result = "This is the result of the calculation";
};
_worker.RunWorkerCompleted += (sender, e) =>
{
// the background work completed, we may no
// present the result to the GUI if no exception
// was thrown in the DoWork method
if (e.Error != null)
{
label1.Text = (string)e.Result;
}
};
_worker.RunWorkerAsync();
}
}
达林已经告诉过你这个理论。
但是你应该检查静态ThreadPool.QueueUserWorkItem
方法。 它更方便。
已经有这个体面的问题,有很多链接到比MSDN更容易消化的文章。
Jon Skeet的文章是最容易开始的文章,也可能是最全面的文章,而Joe Duffy的文章则深入探讨。 浏览Stackoverflow中的C#和多线程标记也可以为您提供一些很好的答案。
您可能会发现避免使用BackgroundWorker
是最快的方法,只需使用Invoke:
void ButtonClick(object sender,EventArgs e)
{
Thread thread = new Thread(Worker);
thread.Start();
}
void Worker()
{
if (InvokeRequired)
{
Invoke(new Action(Worker));
return;
}
MyLabel.Text = "Done item x";
}
有些人喜欢在Stackoverflow上使用BackgroundWorker,有些人则不喜欢(我在2号营地)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.