技术控

    今日:172| 主题:49347
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] IDG Contributor Network: Best practices in .Net asynchronous programming

[复制链接]
女王范 发表于 2016-10-1 15:51:16
48 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x

IDG Contributor Network: Best practices in .Net asynchronous programming-1 (complexity,following,potential,Network,keyword)

  Asynchronous programming enables you to perform resource-intensive I/O operations without having to block on the main or the executing thread of the application. Though beneficial and seemingly easy to implement, it comes with a lot of complexity and risks. The potential risks associated with async programming, particularly using asynchronous programming the wrong way by not following the recommended practices, include deadlocks, process crashes and even slow performance. You should also be proficient in writing, debugging async code.
   Avoid having void return type in async methods

  A method in C# is made an asynchronous method using the async keyword in the method signature. You can have one or more await keywords inside an async method. The await keyword is used to denote the suspension point. An async method in C# can have any one of these return types: Task, Task and void. The "await" keyword is used in an async method to inform the compiler that the method can have a suspension and resumption point.
  Note that when using the TPL, the equivalent of returning void in TPL is async Task. You should be aware that async void is and should only be used for async events. If you use it anywhere else, you would run into errors. In other words, an async method that has void as a return type is not recommended. because async methods that return void have different semantics when you are working with exceptions in your application.
  When an exception occurs in an async method that has a return type of Task or Task, the exception object is stored inside the Task object. On the contrary, if you have an async method with a return type of void, there is no Task object associated. Such exceptions are raised on the SynchronizationContext that was active at the time when the asynchronous method was called. In other words, you cannot handle exceptions raised within an async void method using exception handlers written inside the asynchronous method. Async methods that have a return type of void are also difficult to test due to this difference in error handling semantics. For your information, the SynchronizationContext class in the System.Threading namespace represents a synchronization context in .Net and helps you to queue a task onto another context.
  The following code listing illustrates this. You have two methods namely, Test and TestAsync and the latter throws an exception.
  public class AsyncDemo
     {
         public void Test()
         {
             try
             {
                 TestAsync();
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.Message);
             }
         }
         private async void TestAsync()
         {
             throw new Exception("This is an error message");
         }
     }
  Here is how you can create an instance of the AsyncDemo class and invoke the Test method.
  static void Main(string[] args)
         {
             AsyncDemo obj = new AsyncDemo();
             obj.Test();
             Console.Read();
         }
  The test method makes a call to the TestAsync method and the call is wrapped inside a try-catch block with the intent of handling the exception thrown inside the TestAsync method. However, the exception thrown inside the TestAsync method will never be caught, i.e., handled inside the caller method Test.
   Avoid mixing asynchronous and synchronous code

  You should never have a mix of synchronous and asynchronous code. It is a bad programming practice to block on async code by making calls to Task.Wait or Task.Result. I would recommend using async code end to end – it is the safest way to avoid errors from creeping in.
   You can avoid deadlocks by using . ConfigureAwait(continueOnCapturedContext: false) whenever you make a call to await. If you don't use this, the async method would block at the point where await has been called. In this case you are just informing the awaiter not to capture the current context. I would say that it is a good practice to use .ConfigureAwait(false) unless you have a specific reason to not use it.
   I would discuss more on asynchronous programming in my future blog posts here. For more information on best practices in asynchronous programming, you can refer to Stephen Cleary's great article at MSDN .
   This article is published as part of the IDG Contributor Network.Want to Join?
友荐云推荐




上一篇:Ahead-Of-Time (AOT) Compilation May Come to OpenJDK HotSpot in Java 9
下一篇:[React Native Android 安利系列]ReactNative中的reactjs基础
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表