多线程应用程序

时间:2010-05-09 05:33:45

标签: c# .net winforms multithreading

我一直在阅读有关MSDN的文章,但我的思绪已经死了(这通常发生在我阅读MSDN时(没有攻击MSDN,但你的文章有时会让我感到困惑。)),而我正试图做一些“背景工作“在我的应用程序中,但不知道如何。这只是一种方法。但应用程序挂起,我必须等待1到3分钟才能变成......没变??

是否有任何简单的例子可以在某个地方铺设'我可以看看/玩的地方?

谢谢大家

3 个答案:

答案 0 :(得分:4)

Jon Skeet写了一篇很好的introduction to multithreading in .NET,你可能会读到。它还涵盖threading in 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();
    }
}

答案 1 :(得分:0)

达林已经告诉过你这个理论了。

但是你应该查看静态ThreadPool.QueueUserWorkItem方法。它更方便。

答案 2 :(得分:0)

已经this decent question有很多链接到比MSDN更容易消化的文章。

Jon Skeet的文章是最容易开始的,也可能是最全面的文章,而Joe Duffy的系列则深入探讨。在Stackoverflow中浏览C# & Multithreading标签也可以为您提供一些好的答案。

您可能会发现避免使用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号营地)。

相关问题