c#

如何在C#中创建和管理Task

小樊
94
2024-09-04 13:20:47
栏目: 编程语言

在C#中,Task是一种轻量级的线程,用于执行异步操作

  1. 使用Task.Run创建并启动一个新任务:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        await Task.Run(() =>
        {
            Console.WriteLine("Hello from task!");
        });
    }
}
  1. 使用Task.Factory.StartNew创建并启动一个新任务:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var task = Task.Factory.StartNew(() =>
        {
            Console.WriteLine("Hello from task!");
        });

        await task;
    }
}
  1. 使用TaskCompletionSource<T>创建一个可以手动控制完成状态的任务:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var tcs = new TaskCompletionSource<bool>();

        // Simulate an asynchronous operation
        Task.Run(() =>
        {
            Console.WriteLine("Hello from task!");
            tcs.SetResult(true);
        });

        await tcs.Task;
    }
}
  1. 使用Task.WhenAll等待多个任务完成:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var task1 = Task.Run(() =>
        {
            Console.WriteLine("Task 1");
        });

        var task2 = Task.Run(() =>
        {
            Console.WriteLine("Task 2");
        });

        await Task.WhenAll(task1, task2);
    }
}
  1. 使用Task.WhenAny等待多个任务中的一个完成:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var task1 = Task.Delay(1000).ContinueWith(_ => "Task 1");
        var task2 = Task.Delay(2000).ContinueWith(_ => "Task 2");

        var completedTask = await Task.WhenAny(task1, task2);
        Console.WriteLine($"Completed task: {completedTask.Result}");
    }
}
  1. 取消任务:
using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var cts = new CancellationTokenSource();

        var task = Task.Run(() =>
        {
            while (!cts.Token.IsCancellationRequested)
            {
                Console.WriteLine("Task is running...");
                Thread.Sleep(500);
            }
        }, cts.Token);

        // Cancel the task after 2 seconds
        await Task.Delay(2000);
        cts.Cancel();

        try
        {
            await task;
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Task was canceled.");
        }
    }
}

这些示例展示了如何在C#中创建和管理任务。你可以根据需要调整代码以适应不同的场景。

0
看了该问题的人还看了