zoukankan      html  css  js  c++  java
  • 不同线程之间传递数据

     一般情况下,在线程间是不能交换数据的,不过在相同应用程序域中的线程则可以共享应用程序域的数据。我们可以通过AppDomain的GetData和SetData方法来实现这一功能。具体见源代码。
    using System;
    using System.Threading;
    
    namespace ConsoleDemo
    {
        /// <summary>
        /// Class 的摘要说明。
        /// </summary>
        class Class
        {
            /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            [STAThread]
            static void Main(string[] args)
            {
                //
                // TODO: 在此处添加代码以启动应用程序
                //
                int inputParam = 10;
    
                Thread demoTd = new Thread(new ThreadStart(Run));
                demoTd.IsBackground = true;
    
                Thread.GetDomain().SetData("demo", inputParam);   //设置应用程序域的数据槽的数据
                demoTd.Start();
                Console.Read();
            }
    
            static void Run()
            {
                int tmp = 0;
                Console.WriteLine(tmp);
                try
                {
                    tmp = Convert.ToInt32(Thread.GetDomain().GetData("demo"));  //读取应用程序域中的数据槽数据
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp);
                    Console.Read();
                }
                Console.WriteLine(tmp);
                Console.Read();
            }
        }
    }


  • 相关阅读:
    C#深入浅出 修饰符(二)
    HDU 5785 Interesting
    HDU 5783 Divide the Sequence
    HDU 5781 ATM Mechine
    UVA 714 Copying Books
    uva 1471 Defense Lines
    UVA 11134 Fabled Rooks
    UVA 11572 Unique Snowflakes
    UVA 11093 Just Finish it up
    UVA 10954 Add All
  • 原文地址:https://www.cnblogs.com/zhangqs008/p/3618454.html
Copyright © 2011-2022 走看看