shiy720 发表于 2024-6-15 17:54:45

C# 异步运行不等待


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.

public async Task MyMethodAsync()
{
    await Task.Delay(2000); // Simulate some asynchronous work
    Console.WriteLine("Async work completed!");
}
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.

public void MyMethod()
{
    Task.Run(() =>
    {
      // Perform some CPU-bound work
      for (int i = 0; i < 1000000; i++)
      {
            // Do some work
      }
    });
}
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.

public void MyMethod()
{
    ThreadPool.QueueUserWorkItem((state) =>
    {
      // Perform some I/O-bound work
      using (var client = new WebClient())
      {
            client.DownloadString("https://example.com");
      }
    });
}
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.

public void MyMethod()
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += (sender, e) =>
    {
      // Perform some work
      for (int i = 0; i < 1000000; i++)
      {
            // Do some work
      }
    };
    worker.RunWorkerAsync();
}
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#!
页: [1]
查看完整版本: C# 异步运行不等待