1024programmer News Asynchronous programming Task

Asynchronous programming Task

Try to use asynchronous programming (ASYNC-AWAIT)

The asynchronous programming model was introduced in C#5.0 , and became very popular. ASP.NET Core uses the same asynchronous programming paradigm to make applications more reliable, faster, and more stable.

You should use end-to-end asynchronous programming in your code.

Let’s take an example ;We have an ASP.NET CoreMVC application,with some database operations in the middle. As we know , it may have many layers , it all depends on user’s project architecture , but let’s take a simple example , where we have Controller》Repository layers and so on. Let’s see how to write the sample code at the controller layer.

[HttpGet]
[Route("GetPosts")]
public async Task GetPosts()
{
try
{
var posts = await postRepository.GetPosts();
if (posts == null)
{
return NotFound();
/> }

return Ok(posts);
}
catch (Exception)
{
return BadRequest();

}
}

The following code shows how we implement asynchronous programming at the repository layer.

public async Task<List> GetPosts()
{
if (db != null)
{
return await (from p in db.Post
from c in db.Category
where p.CategoryId == c.Id
select new PostViewModel
{
PostId = p.PostId,
Title = p.Title,
Description = p.Description,
CategoryId = p. CategoryId,
CategoryName = c.Name,
CreatedDate = p.CreatedDate
}).ToListAsync();
}

return null;
}

Use asynchronous programming to avoid TASK.WAIT or TAST.RESULT

When using asynchronous programming , I suggest you avoid Task.Wait and Task.Result and try to use WAIT , for the following reasons :

  1. They block the thread until the task is complete, and wait for the task to complete. Wait synchronously blocks the thread , until the task is complete.

  2. Wait and Task.Result wrap all types of exceptions in AggregateException , and add complexity when performing exception handling. If you’re using await instead of Task.Wait and Task.Result , then you don’t have to worry about exception handling.

  3. Sometimes & # xff0c; they all block the current thread and create a deadlock.

  4. Wait and Task.Result can only be used while parallel task execution is in progress. We recommend that you not use it in asynchronous programming.

Let’s demonstrate the correct use and examples of Task.Wait not recommended ,to deepen understanding!

// Correct example
Task task = DoWork();
await task;

// Deprecated example
Task task = DoWork();
task.Wait();

Let us demonstrate the examples of correct use and irregular use of Task.Result&#xff0c ; Let’s deepen our understanding !

// Good Performance on UI
Task task = GetEmployeeName();
txtEmployeeName.Text & #61; await task;

// Bad Performance on UI
Task task = GetEmployeeName();
txtEmployeeName.Text = task. Result;

Asynchronously perform I/O operations

When performing I/O operations&#xff0c ;You should execute them asynchronously,so as not to affect other processes. An I/O operation means performing some operation on a file , such as uploading or retrieving a file. It can be any operation like : image upload , file upload or anything else. If you try to do it synchronously , then it blocks the main thread and stops other background execution,until the I/O is complete. So & # xff0c; In terms of improving performance & # xff0c; you should always execute asynchronously when doing I/O.

We have many asynchronous methods available for I/O operations , such as ReadAsync, WriteAsync, FlushAysnc, etc. Here is a simple example, how we can create a copy of a file asynchronously.

public async void CreateCopyOfFile()
{
string dir = @"c:\Mukesh\files\";

using (StreamReader objStreamReader= File.OpenText(dir + "test.txt"))
{
using (StreamWriter objStreamWriter= File.CreateText(dir+ "copy_test.txt"))
{
await CopyFileToTarget(objStreamReader, objStreamWriter);
}
}
}

public async Task CopyFileToTarget(StreamReader objStreamReader, StreamWriter objStreamWriter)
{
int num;
char[] buffer = new char[0x1000];

while ((num& #61; await objStreamReader.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
await objStreamWriter.WriteAsync(buffer, 0, num);
}
}

Transfer: https://www.cnblogs.com/laoer/p/10547579.html

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/asynchronous-programming-task/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索