zoukankan      html  css  js  c++  java
  • 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实现!

    转载https://www.cnblogs.com/lori/p/9082847.html;

  • 相关阅读:
    Tomcat日志、项目中的log4j日志、e.printStackTrace()——我的日志最后到底跑哪去了?
    MySQL中有关TIMESTAMP和DATETIME的总结
    org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
    @RequestBody和@RequestParam区别
    Synchronized的jvm实现
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
  • 原文地址:https://www.cnblogs.com/WordHorizon/p/11345883.html
Copyright © 2011-2022 走看看