zoukankan      html  css  js  c++  java
  • C# 异步 async 和 await

    1、 页面头部 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Async="true" %>

    2、 

    protected async void Button1_Click(object sender, EventArgs e)
    {
    //TextBox1.Text = new Class1().Start();

    int contentLength = await AccessTheWebAsync();    //这里会阻塞后面的执行
    TextBox1.Text += "1245";
    TextBox1.Text += contentLength;
    }

    async Task<int> AccessTheWebAsync()  // 这里的返回值类型 Task<T> void  Task
    {
    HttpClient client = new HttpClient();
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    DoIndependentWork();

    string urlContent = await getStringTask;

    return urlContent.Length;

    }

    void DoIndependentWork()
    {
    TextBox1.Text += "Working.......";
    }

    第二种方式:

    public string Start()
    {
    Diaplay();   //这里不会阻止线程执行
    return result.ToString() + "12454";
    }

    public async void Diaplay()
    {
    double result = await GetValueAsync(124.12, 1.122);

    }

    Task<double> GetValueAsync(double num1, double num2)
    {
    return Task.Run(() =>
    {
    for (int i = 0; i < 10000; i++)
    {
    num1 = num1 / num2;
    }
    return num1;
    });
    }

  • 相关阅读:
    7. ZooKeeper的stat结构
    6. ZooKeeper访问控制列表
    5. 监视和ZooKeeper操作
    4. ZooKeeper 基本操作
    3.Apache ZooKeeper数据模型
    Eclipse安装Activiti Designer插件
    Javascript Canvas验证码
    Tomcat9配置SSL连接
    JAVA将异常的堆栈信息转成String
    SpringBoot2静态资料访问
  • 原文地址:https://www.cnblogs.com/xiaocandou/p/4942792.html
Copyright © 2011-2022 走看看