1、通过实体类来传递(可以传递多个参数与获取返回值),demo如下:
需要在线程中调用的函数:
namespace ThreadParameterDemo
{
public class FunctionClass
{
public static string TestFunction(string name, int age)
{
//内部处理省略
return name + " 的年龄是:" + age;
}
}
}通过实体来来封装:namespace ThreadParameterDemo
{
/// <summary>
/// 过渡类
/// </summary>
public class TransitionalClass
{
private string name = string.Empty;
private int age;
public string acceptResults = string.Empty;
public TransitionalClass(string name, int age)
{
this.name = name;
this.age = age;
}
public void TestFunction()
{
acceptResults = FunctionClass.TestFunction(this.name, this.age);
}
}
}调用:
private void Form1_Load(object sender, EventArgs e)
{
//实例化ThreadWithState类,为线程提供参数
TransitionalClass tc = new TransitionalClass(" Jack", 42);
// 创建执行任务的线程,并执行
Thread t = new Thread(new ThreadStart(tc.TestFunction));
t.Start();
//获取返回值,通过 tc.acceptResults;
}
小注:
必须注意IsBackground的问题,如果IsBackground为false的,则Windows程序在退出的时候,不会为你自动退出该线程。也就是实际上你的应用程序未结束。
ThreadStart中的函数是没有返回值和参数的
2、异步调用中的参数和返回值具体代码如下:
public delegate string delegateFunction(string name,int age);//委托
delegateFunction df;
private void Form1_Load(object sender, EventArgs e)
{
//指向需要调用的方法
df = new delegateFunction(FunctionClass.TestFunction);
string name = "my name";//输入参数
int age = 19;
IAsyncResult result = df.BeginInvoke(name,age, null, null);
string myResult = df.EndInvoke(result);//用于接收返回值
MessageBox.Show(myResult);
}简化:
public Func<string, int, string> df;//委托
private void Form1_Load(object sender, EventArgs e)
{
//指向需要调用的方法
df += FunctionClass.TestFunction;
string name = "my name";//输入参数
int age = 19;
IAsyncResult result = df.BeginInvoke(name, age, null, null);
string myResult = df.EndInvoke(result);//用于接收返回值
MessageBox.Show(myResult);
}
小注:
通过这种方式生成新线程是运行在后台的(background),优先级为normal
3、如果不如返回值的时候,应该怎么优雅的写呢?匿名函数啊
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客户端的时间限制,造成造成主程序的莫名崩溃。
原文地址:http://blog.csdn.net/jiankunking/article/details/45932289