• C#学习记录6——异步async 和 await


    async可以声明异步处理过程。

    一般是将方法声明为async,在其中有await内容

     1 private async void StartButton_Click(object sender, RoutedEventArgs e)
     2 {
     3 
     4     ResultsTextBox.Text += "\n";
     5     try
     6     {
     7         int length = await ExampleMethodAsync();
     8         ResultsTextBox.Text += String.Format("Length: {0}\n", length);
     9     }
    10     catch (Exception)
    11     {
    12         // Process the exception if one occurs.
    13     }
    14 }
    15 
    16 public async Task<int> ExampleMethodAsync()
    17 {
    18     var httpClient = new HttpClient();
    19     int exampleInt = (await httpClient.GetStringAsync("http://msdn.microsoft.com")).Length;
    20     ResultsTextBox.Text += "Preparing to finish ExampleMethodAsync.\n";
    21 
    22     return exampleInt;
    23 }
    24 // Output:
    25 // Preparing to finish ExampleMethodAsync.
    26 // Length: 53292

    在声明一个方法时,将其标为async,则说明方法中有await的异步内容。

    调用async时,要使用await关键字。

    在async方法中,会一直执行到await部分,这时将方法挂起,进行其他内容,等待其完成后,完成与其相关的部分。

    如果程序包括从网络中下载获取数据,从文件中读入大量内容,这样占时较多的行为,将其设为异步执行可以很好的使整个程序更加流畅。

    实例来源及参考链接:https://msdn.microsoft.com/zh-cn/library/hh156513.aspx

          https://msdn.microsoft.com/zh-cn/library/hh191443.aspx

    2.Double.Parse和Double.TryParse都可以将字符串转化为double。例如“12345”可以转化为数字的12345

    从名字上看,tryparse是不确定的转化,即在不确定string是否可以转换成double时使用。

    当然,如果传入parse中的string也无法转换为double,也会出现错误。

    两者的不同在于

      tryparse返回值类型为boolean,也就是说如果无法转换,就直接返回false

      而parse会直接转换,如果无法转换,会throw exception,内部如果无法解决,就会抛出方法。

      所以说,tryparse一般是用在if这样的语句里面例如:if(doublt.TryParse(str)){...}; 而parse是直接用赋值的,例如:double db=double.Parse(str);

      更多时候,TryParse是用另一种用法: double db; if(doublt.TryParse(str, out db)){...};如果转换成功,将db赋值为该值

  • 相关阅读:
    Spring(八)-spring5框架新功能
    Spring(七)-事务操作
    Spring(五)-AOP
    Linux errno错误码
    思考:如何保证服务稳定性?
    CPU性能分析工具原理
    Oracle数据库url格式
    java对象的四种引用:强引用、软引用、弱引用和虚引用
    给老板汇报技术规划的要点
    后端程序员必备:分布式事务基础篇
  • 原文地址:https://www.cnblogs.com/sywang/p/4439506.html
Copyright © 2020-2023  润新知