在不同線程之間傳遞資料

來源:互聯網
上載者:User
        一般情況下,線上程間是不能交換資料的,不過在相同應用程式定義域中的線程則可以共用應用程式定義域的資料。我們可以通過AppDomain的GetData和SetData方法來實現這一功能。具體見原始碼。
       

 1using System;
 2using System.Threading;
 3
 4namespace ConsoleDemo
 5{
 6    /**//// <summary>
 7    /// Class1 的摘要說明。
 8    /// </summary>
 9    class Class1
10    {
11        /**//// <summary>
12        /// 應用程式的主進入點。
13        /// </summary>
14        [STAThread]
15        static void Main(string[] args)
16        {
17            //
18            // TODO: 在此處添加代碼以啟動應用程式
19            //
20            int inputParam = 10;
21            
22            Thread demoTd = new Thread(new ThreadStart(Run));
23            demoTd.IsBackground = true;
24
25            Thread.GetDomain().SetData("demo", inputParam);   //設定應用程式定義域的資料槽的資料
26            demoTd.Start();
27            Console.Read();
28        }
29
30        static void Run()
31        {
32            int tmp = 0;
33            Console.WriteLine(tmp);
34            try
35            {
36                tmp = Convert.ToInt32(Thread.GetDomain().GetData("demo"));  //讀取應用程式定義域中的資料槽資料
37            }
38            catch(Exception exp)
39            {
40                Console.WriteLine(exp);
41                Console.Read();
42            }
43            Console.WriteLine(tmp);
44            Console.Read();
45        }
46    }
47}
48

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.