簡體   English   中英

多線程應用程序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM