1. 程式人生 > >對執行緒的一點點新理解

對執行緒的一點點新理解

最近在做一個提示框,要用到執行緒,遇到的問題是不知道怎麼在一個類中用同一個執行緒來呼叫所有方法。

後來想,是不是隻要線上程中建立了這個類,那這個類裡的所有原生的東西都屬於這個執行緒。

於是寫了個簡單的程式試了下:

    public class Class1
    {
        public void Method1()
        {
            Console.WriteLine("{0} - {1} - {2}",
                "Class1",
                "Method1",
                Thread.CurrentThread.ManagedThreadId);
        }

        public void Method2()
        {
            Console.WriteLine("{0} - {1} - {2}",
                "Class1",
                "Method2",
                Thread.CurrentThread.ManagedThreadId);
        }

        public void Method3()
        {
            Console.WriteLine("{0} - {1} - {2}",
                "Class1",
                "Method3",
                Thread.CurrentThread.ManagedThreadId);
        }
    }

    public class Class1Caller
    {
        public void CallClass1()
        {
            Task.Factory.StartNew(
                delegate
                {
                    Console.WriteLine("{0} - {1} - {2}",
                        "Class1Caller",
                        "CallClass1",
                        Thread.CurrentThread.ManagedThreadId);
                    Class1 c1 = new Class1();
                    c1.Method1();
                    c1.Method2();
                    c1.Method3();
                });
        }
    }

    public class Class2
    {
        public void CallClass2()
        {
            this.Method1();
            this.Method2();
            this.Method3();
        }

        private void Method1()
        {
            Task.Factory.StartNew(
                delegate
                {
                    Console.WriteLine("{0} - {1} - {2}",
                        "Class2",
                        "Method1",
                        Thread.CurrentThread.ManagedThreadId);
                });
        }

        private void Method2()
        {
            Task.Factory.StartNew(
                delegate
                {
                    Console.WriteLine("{0} - {1} - {2}",
                        "Class2",
                        "Method2",
                        Thread.CurrentThread.ManagedThreadId);
                });
        }

        private void Method3()
        {
            Task.Factory.StartNew(
                delegate
                {
                    Console.WriteLine("{0} - {1} - {2}",
                        "Class2",
                        "Method3",
                        Thread.CurrentThread.ManagedThreadId);
                });
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Class1Caller c1c = new Class1Caller();
            Class2 c2 = new Class2();

            c1c.CallClass1();
            c2.CallClass2();

            Console.ReadLine();
        }
    }


測試結果:


證明我的設想是正確的。