• c#_delegate_异步调用_BeginInvoke


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    //异步调用
    //IAsyncResult BeginInvoke(argument,AsyncCallback callback,object asynState)
    //argument - 如果没有参数,callback就是第一个参数
    //BeginInvoke返回值是IAsyncResult
    //AsyncState - 传递给异步调用的那个状态对象
    //AsyncWaitHandle - 在异步操作完成前,一直使用WaitHandle阻断调用线程
    //CompleteSynchronously - 指示一步操作是否同步完成
    //IsCompleted - 指示异步操作已经完成
    
    namespace Starter
    {
        public delegate void DeleageteClass();
    
        class Program
        {
            static void Main(string[] args)
            {
                DeleageteClass del = MethodA;
    
                DelegateStateBag state = new DelegateStateBag();
    
                IAsyncResult ar = del.BeginInvoke(Callback,state);
    
                if (ar.IsCompleted == true)
                {
                    Console.WriteLine("MethodA completed");
                }
                else
                {
                    Console.WriteLine("MethodA not completed");
                }
                
                ar.AsyncWaitHandle.WaitOne();
    
                //do something else
                
                //Sleep - 不然会产生竞争,同时启动Callback和main,Sleep是消除竞争的根本办法
                Thread.Sleep(100);
    
                lock (state)
                {
                    Console.WriteLine("Back in main");
                    Console.WriteLine(state.message);
                }
    
                Console.ReadLine();
            }
    
            public static void Callback(IAsyncResult ar)
            {
                DelegateStateBag state = (DelegateStateBag)ar.AsyncState ;
                lock(state)
                {
                    Console.WriteLine("Call back running");
                    ((DelegateStateBag)ar.AsyncState).message = 
                        "State object modify in callack";
                }
    
            }
    
    
            public static void MethodA()
            {
                Console.WriteLine("MethodA running....");
                Thread.Sleep(200);
            }
        }
    
        class DelegateStateBag
        {
           public string message;
        }
    }
    


  • 相关阅读:
    排序入门练习题3 谁考了第k名 题解
    排序入门练习题2 从大到小排序 题解
    排序入门练习题1 排序 题解
    关于这个博客
    Count Good Substrings
    Long Long Message
    Milk Patterns
    Musical Theme
    Life Forms
    New Distinct Substrings
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720450.html
Copyright © 2020-2023  润新知