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;
    });
    }

  • 相关阅读:
    Java设计模式之依赖倒置原则
    windows 下安装apache 遇到的问题
    Java序列化相关
    批量插入————优化
    接口相关
    Redis使用及工具类
    面试回顾——kafka
    面试回顾——List<T>排序
    Java面试——线程池
    面试回顾——session相关
  • 原文地址:https://www.cnblogs.com/xiaocandou/p/4942792.html
Copyright © 2011-2022 走看看