This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging
The introduction
Prior to the.net Framework 4.5 era, the usual way to call asynchronous multithreading was to use the Thread class. Today, our protagonist is Task. When to use asynchronous IO and when to use multithreading. A lot of people don’t distinguish between cpu-bound and IO-bound, now. Let’s talk about asynchronous applications
Simple use β€
First, let’s talk about our requirements: in real development, we usually need some delays.
For example: 30 seconds after the user clicks [post boiling point], if 5 people click like this boiling point (assuming that the forum is real-time). Then the boiling point will be immediately recommended to the hot boiling point (a section of the forum)
Let’s implement its function:
- Define the
ThumbsUp
: It’s used to keep track of likes,JsonResult<T>
: Its function is to return processing results and status information
public class JsonResult<T>
{
public JsonResult(T result)
{
Result = result;
Status = HttpStatusCode.OK;
}
public HttpStatusCode Status { get; set; }
public string ErrMsg { get; set; }
public T Result { get; set; }}public class ThumbsUp
{
public string UserId { get; set; }}Copy the code
- Implementation of publish and like functionality
As you can see from the Publish method, we get the ILogger instance via the IServiceProvider GetService method
TIPS: Why not inject an ILogger into the constructor?
In fact, we use the task.factory. StartNew method to open a new thread, and the logger is usually connected to a releasable resource such as a database, when used in the new thread. The Controller might have been released (and so would the recorder), causing an exception that accesses the freed object.
- Visit the API to see it in action:
First, let’s go to the URL :pins/ Like and refresh it five times to get the number of Likes above five. Then, go to the URL: pins/ Publish to simulate the publish boiling point and see a screenshot of the code in action:
A little thought π
We just used task.factory. StartNew to create a thread to complete the subsequent tasks. The above method is not recommended because it blocks a thread that is waiting for the response to complete. This reduces the number of threads available in the Asp.net Core thread pool. As a result, server performance deteriorates
Use asynchronous IOπ¨
Look at the following code:
[ApiController]
[Route("[controller]/[action]")]
public class PinsController : ControllerBase
{
/// <summary>
///Think of it as a value from a database
/// </summary>
public readonly static List<ThumbsUp> Likes = new List<ThumbsUp>();
private readonly IServiceProvider _sp;
public PinsController(IServiceProvider sp)
{
_sp = sp;
}
[HttpGet]
public async Task<JsonResult<bool>> Publish()
{
//step1: a series of operations... Record to database
var logger = _sp.GetService<ILogger<PinsController>>();
// Step2: Count the number of likes 30 seconds after the release, notify users and push to the hot boiling point
_ = Task.Delay(TimeSpan.FromSeconds(30)).ContinueWith(_ =>
{
if (Likes.Count >= 5)
{
//step1: push to the hotspot....
//step2: notify the user
logger.LogError("It's time: {0}, we pretend to notify the user...", DateTime.Now.ToString("HH:mm:ss")); }});await Task.CompletedTask;
return new JsonResult<bool> (true) { ErrMsg = DateTime.Now.ToString("HH:mm:ss")}; } [HttpGet]
public bool Like()
{
Likes.Add(new ThumbsUp { UserId = Guid.NewGuid().ToString() });
return true; }}Copy the code
We first use async/await, which helps us create an asynchronous state machine, then modify task.factory. StartNew to task.delay and create a continuation Task for it. In the continuation task, the corresponding business logic has been done. And the deprecated metamodel is used to eliminate the warning. How is this different from the StartNew method?
The StartNew method is often referred to as cpu-bound, which first returns a Response and then simply opens a thread block to complete the business logic. With async/await (iO-bound) it does not generate new threads, but merely generates code into an asynchronous state machine. The result continues to be processed in the form of an asynchronous callback
References π
References:
- Docs.microsoft.com/en-us/dotne…
- Docs.microsoft.com/en-us/dotne…
Write in the last
This article lacks some sense of story… Later time to improve