找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 40|回复: 0

[工具类] C# 异步运行不等待

[复制链接] IP属地:广东省广州市
发表于 2024-6-15 17:54:45 | 显示全部楼层 |阅读模式

You want to talk about asynchronous programming in C#! 😊

In C#, asynchronous programming allows you to write code that can perform multiple tasks concurrently, improving the responsiveness and performance of your application. Here are some ways to run asynchronous code in C#:

1. Async/Await

The async and await keywords are used to write asynchronous code that's easy to read and maintain. When you use async/await, the compiler generates a state machine that manages the asynchronous operation for you.

  1. public async Task MyMethodAsync()
  2. {
  3.     await Task.Delay(2000); // Simulate some asynchronous work
  4.     Console.WriteLine("Async work completed!");
  5. }
复制代码

2. Task.Run

The Task.Run method creates a new task that runs a delegate asynchronously. This is useful when you want to perform some CPU-bound work in the background.

  1. public void MyMethod()
  2. {
  3.     Task.Run(() =>
  4.     {
  5.         // Perform some CPU-bound work
  6.         for (int i = 0; i < 1000000; i++)
  7.         {
  8.             // Do some work
  9.         }
  10.     });
  11. }
复制代码

3. ThreadPool

The ThreadPool class provides a pool of worker threads that can be used to perform asynchronous work. This is useful when you want to perform some I/O-bound work, such as making a network request.

  1. public void MyMethod()
  2. {
  3.     ThreadPool.QueueUserWorkItem((state) =>
  4.     {
  5.         // Perform some I/O-bound work
  6.         using (var client = new WebClient())
  7.         {
  8.             client.DownloadString("https://example.com");
  9.         }
  10.     });
  11. }
复制代码

4. BackgroundWorker

The BackgroundWorker class is a component that allows you to run a task asynchronously in the background. This is useful when you want to perform some work in the background and report progress to the UI.

  1. public void MyMethod()
  2. {
  3.     BackgroundWorker worker = new BackgroundWorker();
  4.     worker.DoWork += (sender, e) =>
  5.     {
  6.         // Perform some work
  7.         for (int i = 0; i < 1000000; i++)
  8.         {
  9.             // Do some work
  10.         }
  11.     };
  12.     worker.RunWorkerAsync();
  13. }
复制代码

When to use each approach?

async/await: When you want to write asynchronous code that's easy to read and maintain.
Task.Run: When you want to perform some CPU-bound work in the background.
ThreadPool: When you want to perform some I/O-bound work, such as making a network request.
BackgroundWorker: When you want to perform some work in the background and report progress to the UI.
Remember, when using asynchronous programming, it's essential to consider the following:

Avoid blocking: Avoid blocking the UI thread or other threads with long-running synchronous operations.
Use asynchronous APIs: Use asynchronous APIs and libraries to perform I/O-bound operations, such as making network requests or reading/writing files.
Handle errors: Handle errors and exceptions properly in your asynchronous code to ensure that your application remains stable and responsive.
By following these best practices, you can write efficient and responsive asynchronous code in C#!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|西兴社区 ( 蜀ICP备2022005627号 )|网站地图

GMT+8, 2024-9-8 11:25 , Processed in 0.634442 second(s), 21 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表