zoukankan      html  css  js  c++  java
  • 委托的异步编程和同步编程的使用( Invoke 和BeginInvoke)

    一,区别:

    使用Invoke完成一个委托方法的封送,就类似于使用SendMessage方法来给界面线程发送消息,是一个同步方法。也就是说在Invoke封送的方法被执行完毕前,Invoke方法不会返回,从而调用者线程将被阻塞。

    使用BeginInvoke方法封送一个委托方法,类似于使用PostMessage进行通信,这是一个异步方法。也就是该方法封送完毕后马上返回,不会等待委托方法的执行结束,调用者线程将不会被阻塞。但是调用者也可以使用EndInvoke方法或者其它类似WaitHandle机制等待异步操作的完成。

    二,使用ASPX页面和浏览器测试页面响应速度

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                Test t = new Test();
                Action<string> action = new Action<string>(t.Say);
                action.BeginInvoke("Demoyibu", null, null);   //这个是异步的方法
                //action.Invoke("Demotongbu");   //这个是同步的方法
                Label1.Text = "显示结果:";
                if (string.IsNullOrEmpty(t.T))
                {
                    Label2.Text = "Demoyibu";
                }
                else
                {
                    Label2.Text = t.T;
                }
            }
        }
        public class Test
        {
            public string T { get; set; }
            public void Say(string a)
            {
                int j = 0;
                for (int i = 0; i < 1000000000; i++)
                {
                    j = i;
                }
                this.T = a;
            }
        }
    }

    页面

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title></title>
    </head>
    <body>
        <form id="form1" action="#">
            <div>
                <asp:Label ID="Label1" runat="server"></asp:Label>
                <asp:Label ID="Label2" runat="server"></asp:Label>
            </div>
        </form>
    </body>
    </html>

    三,查看结果

    异步使用:在异步使用,循环耗时在异步执行,耗时只是页面加载

    同步使用:由于页面返回要加载以上代码的同步循环,所以耗时比较多

  • 相关阅读:
    cf round #421 div2 D. Mister B and PR Shifts
    cf round #421 div2 C. Mister B and Boring Game(trick)
    UVa 12716 GCD XOR
    cf 821E Okabe and El Psy Kongroo(矩阵快速幂)
    hdu 6109 数据分割(并查集+set)
    poj 2887 Big String(块状链表)
    hdu 6119 小小粉丝度度熊(区间双指针)
    hdu 6118 度度熊的交易计划(可行费用流)
    hdu 6015 Gameia(树上博弈)
    hdu 6096 String(AC自动机巧妙建图)
  • 原文地址:https://www.cnblogs.com/May-day/p/7026573.html
Copyright © 2011-2022 走看看