首页 技术 正文
技术 2022年11月14日
0 收藏 690 点赞 2,143 浏览 1576 个字

很久没有写博客了,最近的项目不用写代码。今天没事就看看thread之间的参数传递方式,这里主要适用于运行在不同线程的两个方法之间参数传递。直接看代码

1。方法之间直接传递参数

   void DemoParam()
{
Console.WriteLine("DemoParam:" + Thread.CurrentThread.ManagedThreadId);
//Thread t = new Thread(new ParameterizedThreadStart(testparam));
//t.Start("majaing");
ThreadPool.QueueUserWorkItem(new WaitCallback(testparam),"majaing");
}
void testparam(object obj)
{
Console.WriteLine("DemoParam:" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(obj.ToString());
}

2。借助Static

 //[ThreadStatic]
static string namekey;
void DemoStatic()
{
Console.WriteLine("Static:" + Thread.CurrentThread.ManagedThreadId);
namekey = "majiang";
ThreadPool.QueueUserWorkItem(new WaitCallback(testStatic));
}
void testStatic(object obj)
{
Console.WriteLine("Static:" + Thread.CurrentThread.ManagedThreadId); Console.WriteLine(namekey);
}

3。借助AppDomain

 void DemoAppDomain()
{
Console.WriteLine("AppDomain:"+Thread.CurrentThread.ManagedThreadId);
AppDomain.CurrentDomain.SetData("name", "majiang");
ThreadPool.QueueUserWorkItem(new WaitCallback(testAppDomain));
}
void testAppDomain(object obj)
{
Console.WriteLine("AppDomain:"+Thread.CurrentThread.ManagedThreadId);
var a = AppDomain.CurrentDomain.GetData("name");
Console.WriteLine(a);
}

4。借助CallContext

  void DemoCallContext()
{
Console.WriteLine("CallContext"+Thread.CurrentThread.ManagedThreadId);
// ExecutionContext.SuppressFlow();
CallContext.LogicalSetData("name", "majiang");
ThreadPool.QueueUserWorkItem(new WaitCallback(testCallContext)); }
void testCallContext(object obj)
{
Console.WriteLine("CallContext"+Thread.CurrentThread.ManagedThreadId);
var a = CallContext.LogicalGetData("name");
Console.WriteLine(a);
}

注意里面的注释哦。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905