在另一个线程中进行计算

时间:2011-12-13 19:17:31

标签: c# winforms multithreading

我正在VS2010中编写一个C#windows窗体应用程序。 我有一个功能,可以进行大量的计算。当我按下此功能按钮时,我的程序会停止响应任何点击,直到计算结束。

如何制作窗口窗体并且这些计算并行运行?

4 个答案:

答案 0 :(得分:1)

  • 您可以使用backgroundworker,易于使用 - 将使用内置线程池,更少
    与您使用新thread

  • 的开销相比
  • 您还可以使用详细信息,例如action,然后通过回调拨打begininvoke.

示例(背景工作者):

using System;
using System.Collections.Generic;
using System.ComponentModel;  
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var back = new BackgroundWorker();
            back.DoWork += new DoWorkEventHandler(back_DoWork);
            back.RunWorkerCompleted += new  RunWorkerCompletedEventHandler(back_RunWorkerCompleted);
            back.RunWorkerAsync();
        }

        //Do work here (not safe to call control elemnts here - if so, use this.invoke(deligate);
        private decimal myResult = 0;
        void back_DoWork(object sender, DoWorkEventArgs e)
        {
            myResult = 5 + 5;
        }

        //Update form here - threadsafe
        void back_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            label1.Text = "result: " + myResult.ToString();
        }
    }
}

示例begininvoke:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Action DoWork = new Action(CalcHere);
        DoWork.BeginInvoke(new AsyncCallback(CallBack), null);
    }

    //Work here
    private decimal myResult = 0;
    private void CalcHere()
    {
        myResult = 5 + 5;
    }

    //callback here
    private void CallBack(IAsyncResult result)
    {
        this.Invoke((Action)(() => { label1.Text = "Result: " + myResult.ToString(); }));
    }
}

答案 1 :(得分:0)

您应该使用BackgroundWorker。请查看文档中的Fibonacci计算器示例。

答案 2 :(得分:0)

var calculations = new Thread(() => DoCalculations());

private void DoCalculations() {
    // Do long work
    // ...
}

答案 3 :(得分:0)

愿这对你有用吗?

public class Calculator
{
    public void doHeavyCalculations()
    {
       //Do what you want to here.
    }

};

在你的onButtonClick上,你可以这样做:

Calculator calc = new Calculator();
Thread mThread = new Thread( new ThreadStart(calc.doHeavyCalculations) );

mThread.Start(); //This will start the work

/*
Make some code to show a messagebox to tell users to wait while the calculations are being done. Dont forget to tell the form to update, so it'll show the progress.
*/