码迷,mamicode.com
首页 > 编程语言 > 详细

C# 同一应用程序域不同线程之间的参数传递方式

时间:2014-11-06 19:31:47      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   div   on   

很久没有写博客了,最近的项目不用写代码。今天没事就看看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);
        }

注意里面的注释哦。

 

C# 同一应用程序域不同线程之间的参数传递方式

标签:style   blog   io   color   ar   os   sp   div   on   

原文地址:http://www.cnblogs.com/majiang/p/4079200.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!