基礎才是重中之重~delegate里的Invoke和BeginInvoke


回到目錄

Invoke和BeginInvoke都是調用委托實體的方法,前者是同步調用,即它運行在主線程上,當Invode處理時間長時,會出現阻塞的情況,而BeginInvod是異步操作,它會從新開啟一個線程,所以不會租塞主線程,在使用BeginInvoke時,如果希望等待執行的結果 ,可以使用EndInvoke來實現,這在.net framework4.5之后,被封裝成了async+await來實現,代碼更簡潔,更容易理解。

        delegate void test();
        static void Main(string[] args)
        {
            test ts = new test(TestDelegate);
            ts.Invoke(); //不會產生新線程
            Console.WriteLine("hello");
        }

        internal static void TestDelegate()
        {
            Thread.Sleep(1000);
        }

此時,在主線程中出現了1秒的租塞,因為Invoke是同步的。

下面再來看一下BeginInvoke的實現

        delegate string test();
        static void Main(string[] args)
        {
            test ts = new test(TestDelegate);
           IAsyncResult result = ts.BeginInvoke(null,null); //會在新線程中執行
            string resultstr=ts.EndInvoke(result);
            Console.WriteLine(resultstr);
        }

        internal static string TestDelegate()
        {
            Thread.Sleep(1000);
            return "hello"
        }

上面的代碼會在新線程中執行,並且平會對主線程產生租塞,同時它可以獲取自己的返回值,使用EndInvoke實現!

感謝閱讀!小小的知識點我們也要好好理解。

回到目錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM