3、使用 BackgroundWorker
  多线程返回值简单方法是:使用 BackgroundWorker 组件来管理线程,在任务完成时引发事件,然后用事件处理程序处理结果。
  小注:
  BackgroundWorker 组件用来执行诸如数据库事务、文件下载等耗时的异步操作。
  在应用程序中添加一个BackgroundWorker实例,如果用的是VS,可以从工具上直接拖到应用程序:
  BackgroundWorker backgroundWorker1 = new BackgroundWorker();
  为了开始在后台操作,必须调用BackgroundWorker的RunWorkerAsync()方法,当调用此方时,BackgroundWorker 通过触发DoWork 事件,开始执行后台操作,DoWork 事件的代码是在另一个线程里执行的。
  当后台操作完成以后,无论是completed 还是cancelled,则RunWorkerCompleted 事件被触发,通过此方法可以将后台操作的完成结果反馈给用户。
  另外,通过RunWorkerCompletedEventArgs实例的Cancelled 属性,以判断是否是Cancel操作使得后台操作终止。
  具体demo如下:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
//TransitionalClass tc = new TransitionalClass("xiaoming", 10);
//ThreadPool.QueueUserWorkItem(new WaitCallback(TransitionalClass.TestFunction), tc);
}
private void button1_Click(object sender, EventArgs e)
{
this.TestArea2();
}
private System.ComponentModel.BackgroundWorker BackgroundWorker1
= new System.ComponentModel.BackgroundWorker();
private void TestArea2()
{
InitializeBackgroundWorker();
AreaClass2 AreaObject2 = new AreaClass2();
AreaObject2.Base = 30;
AreaObject2.Height = 40;
// Start the asynchronous operation.
BackgroundWorker1.RunWorkerAsync(AreaObject2);
}
private void InitializeBackgroundWorker()
{
// Attach event handlers to the BackgroundWorker object.
BackgroundWorker1.DoWork +=
new System.ComponentModel.DoWorkEventHandler(BackgroundWorker1_DoWork);
BackgroundWorker1.RunWorkerCompleted +=
new System.ComponentModel.RunWorkerCompletedEventHandler(BackgroundWorker1_RunWorkerCompleted);
}
private void BackgroundWorker1_DoWork(
object sender,
System.ComponentModel.DoWorkEventArgs e)
{
//在执行DoWork 事件时,DoWorkEventArgs 实例的Result 属性,返回值到用户;在RunWorkerCompleted 事件里,RunWorkerCompletedEventArgs 实例的Result 属性接收值;
AreaClass2 AreaObject2 = (AreaClass2)e.Argument;
// Return the value through the Result property.
e.Result = AreaObject2.CalcArea();
}
private void BackgroundWorker1_RunWorkerCompleted(
object sender,
System.ComponentModel.RunWorkerCompletedEventArgs e)
{
// Access the result through the Result property.
double Area = (double)e.Result;
MessageBox.Show("The area is: " + Area.ToString());
}
}
}
  demo代码来自MSDN:点击打开链接
  参考文章:点击打开链接
  4、如果不如返回值的时候,应该怎么优雅的写呢?匿名函数啊
  FunctionClass类新增,测试函数如下:
  public static void TestFunction2(string name, int age)
  {
  //内部处理省略
  }
  调用如下:
  private void Form1_Load(object sender, EventArgs e)
  {
  Thread t1 = new Thread(new ThreadStart(delegate
  {
  FunctionClass.TestFunction2("eee", 5);
  }));
  t1.Start();
  }
  小注:
  如果通过WCF来调用的话,应该把起线程的函数放到服务端,如果放到客户端,很容易因为WCF客户端的时间限制,造成造成主程序的莫名崩溃。
  崩溃的原因主要是客户端wcf响应时间是有限制。