当前位置: 移动技术网 > IT编程>开发语言>c# > C#中的多线程多参数传递详解

C#中的多线程多参数传递详解

2019年07月18日  | 移动技术网IT编程  | 我要评论
之前做了一个小的应用程序,用的是c#语言,涉及到了多线程的多参数传递,经过查找资料总结了一下解决方案! 第一种解决方案的原理是:将线程执行的方法和参数都封装到一个类里面。

之前做了一个小的应用程序,用的是c#语言,涉及到了多线程的多参数传递,经过查找资料总结了一下解决方案!

第一种解决方案的原理是:将线程执行的方法和参数都封装到一个类里面。通过实例化该类,方法就可以调用属性来实现间接的类型安全地传递多个参数。看如下代码:

复制代码 代码如下:

using system;
using system.threading;

//threadwithstate 类里包含了将要执行的任务以及执行任务的方法
public class threadwithstate {
//要用到的属性,也就是我们要传递的参数
private string boilerplate;
private int value;

//包含参数的构造函数
public threadwithstate(string text, int number)
{
boilerplate = text;
value = number;
}

//要丢给线程执行的方法,本处无返回类型就是为了能让threadstart来调用
public void threadproc()
{
//这里就是要执行的任务,本处只显示一下传入的参数
console.writeline(boilerplate, value);
}
}


----------分隔线-----------
复制代码 代码如下:

//用来调用上面方法的类,是本例执行的入口
public class example {
public static void main()
{
//实例化threadwithstate类,为线程提供参数
threadwithstate tws = new threadwithstate(
“this report displays the number {0}.”, 42);

// 创建执行任务的线程,并执行
thread t = new thread(new threadstart(tws.threadproc));
t.start();
console.writeline(“main thread does some work, then waits.”);
t.join();
console.writeline(
“independent task has completed; main thread ends.”);
}
}


从上面的例子就能很清楚的得到我们想要的结果,注意这句代码的用法:
thread t = new thread(new threadstart(tws.threadproc));

第二种解决方案的原理是把多个参数封装成object来传递,然后在线程里使用时拆箱即可,看如下代码:

复制代码 代码如下:

parameterizedthreadstart parstart = new parameterizedthreadstart(threadmethod);
thread mythread = new thread(parstart);
object o = “hello”;
mythread.start(o);

threadmethod如下:
public void threadmethod(object parobject)
{
//程序代码
}

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网