如何使用C# Task處理并發(fā)任務(wù)

c#
小樊
85
2024-09-04 13:17:48
欄目: 編程語言

在C#中,Task類是用于表示異步操作的一種方式

  1. 創(chuàng)建并啟動(dòng)一個(gè)簡(jiǎn)單的任務(wù):
using System;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        Task task = Task.Run(() =>
        {
            Console.WriteLine("Running a task on a separate thread.");
        });

        // 等待任務(wù)完成
        task.Wait();
    }
}
  1. 使用asyncawait關(guān)鍵字處理異步方法:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        await RunAsyncTask();
    }

    static async Task RunAsyncTask()
    {
        await Task.Run(() =>
        {
            Console.WriteLine("Running an asynchronous task on a separate thread.");
        });
    }
}
  1. 處理多個(gè)并發(fā)任務(wù):
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        Task task1 = Task.Run(() =>
        {
            Console.WriteLine("Running task 1 on a separate thread.");
        });

        Task task2 = Task.Run(() =>
        {
            Console.WriteLine("Running task 2 on a separate thread.");
        });

        // 等待所有任務(wù)完成
        await Task.WhenAll(task1, task2);
    }
}
  1. 處理任務(wù)返回值:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        Task<int> task = Task.Run(() =>
        {
            Console.WriteLine("Running a task with return value on a separate thread.");
            return 42;
        });

        int result = await task;
        Console.WriteLine($"The result is: {result}");
    }
}
  1. 處理多個(gè)并發(fā)任務(wù)并獲取結(jié)果:
using System;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        Task<int>[] tasks = new[]
        {
            Task.Run(() =>
            {
                Console.WriteLine("Running task 1 on a separate thread.");
                return 1;
            }),
            Task.Run(() =>
            {
                Console.WriteLine("Running task 2 on a separate thread.");
                return 2;
            })
        };

        // 等待所有任務(wù)完成并獲取結(jié)果
        int[] results = await Task.WhenAll(tasks);
        Console.WriteLine($"The results are: {string.Join(", ", results)}");
    }
}

這些示例展示了如何使用C# Task類處理并發(fā)任務(wù)。請(qǐng)注意,為了確保代碼的可讀性和可維護(hù)性,建議使用asyncawait關(guān)鍵字來處理異步操作。

0