C#中的多线程多参数传递详解
时间:2023-08-02 22:23:46
之前做了一个小的应用程序,用的是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)
{
//程序代码
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#学习笔记之状态模式详解
![](https://img.aspxhome.com/file/2023/0/122710_0s.png)
java web手写实现分页功能
![](https://img.aspxhome.com/file/2023/8/63028_0s.jpg)
Unity3D运行报DllNotFoundException错误的解决方案
![](https://img.aspxhome.com/file/2023/0/78150_0s.png)
IDEA部署JavaWeb项目到Tomcat服务器的方法
Android Studio 引用外部依赖时报错的解决方法
springBoot加入thymeleaf模板的方式
![](https://img.aspxhome.com/file/2023/6/60056_0s.png)
Android编程之SMS读取短信并保存到SQLite的方法
![](https://img.aspxhome.com/file/2023/3/139003_0s.png)
java WSDL接口webService实现方式
![](https://img.aspxhome.com/file/2023/9/84239_0s.png)
IDEA高效使用设置指南
![](https://img.aspxhome.com/file/2023/7/108377_0s.jpg)
SpringBoot零基础入门之基本操作与概念
![](https://img.aspxhome.com/file/2023/3/128853_0s.png)
Android使用PhotoView实现图片双击放大单击退出效果
解析Java的Spring框架的BeanPostProcessor发布处理器
![](https://img.aspxhome.com/file/2023/0/65170_0s.png)
Android Room数据库多表查询的使用实例
![](https://img.aspxhome.com/file/2023/4/114314_0s.jpg)
springboot整合security和vue的实践
![](https://img.aspxhome.com/file/2023/5/97985_0s.jpg)
谈谈对Java中的volatile的理解
![](https://img.aspxhome.com/file/2023/3/101953_0s.png)
Java如何使用spire进行word文档的替换详解
![](https://img.aspxhome.com/file/2023/1/85561_0s.jpg)
java关于并发模型中的两种锁知识点详解
Android中资源文件用法简单示例
java实现静默加载Class示例代码
springboot读取配置文件中的参数具体步骤
![](https://img.aspxhome.com/file/2023/2/59582_0s.png)