不同线程之间传递数据

 一般情况下,在线程间是不能交换数据的,不过在相同应用程序域中的线程则可以共享应用程序域的数据。我们可以通过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();
        }
    }
}


posted @ 2013-05-15 19:41  清山博客  阅读(396)  评论(0编辑  收藏  举报