简体   繁体   中英

Multithreaded Applications

I have been reading the articles on MSDN, but my mind is dead (this usually happens when I read MSDN (No offense MSDN, but your articles confuse me at times.)), and I'm trying to do some "background work" in my app, but not sure how. It's just a single method. But the application hangs, and I have to wait up to 1 - 3 minutes for it to become ...unhanged?

Are there any simple examples that are laying 'round online somewhere that I can have a look at/play around with?

Thank you all

Jon Skeet wrote a nice introduction to multithreading in .NET that you might read. It also covers threading in WinForms . It may go among the lines:

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();
    }
}

Darin already told you the theory.

But you should check out the static ThreadPool.QueueUserWorkItem method. It's more convenient.

There is already this decent question with lots of links to articles that are more easily digestable than MSDN.

Jon Skeet's article is the easiest and probably the most comprehensive to get started with, and Joe Duffy's series goes into a lot of depth. Browsing the C# & Multithreading tags in Stackoverflow also gives you some good answers.

You might find avoiding the BackgroundWorker the fastest way to get going, and simply use an 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";
}

Some people like using the BackgroundWorker on Stackoverflow, others don't (I'm in camp number 2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM