溫馨提示×

c#異步開發(fā)如何處理超時

c#
小樊
81
2024-10-18 21:48:57
欄目: 編程語言

在C#中,處理異步操作的超時可以采用以下方法:

  1. 使用Task.WhenAnyTask.WhenAll方法:

Task.WhenAny方法允許你在一組任務中等待任何一個任務完成。這對于超時處理非常有用。你可以創(chuàng)建一個CancellationTokenSource,并將其傳遞給Task.WhenAny方法。如果在指定的超時時間內沒有任務完成,你可以取消任務并處理超時。

示例:

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        CancellationTokenSource cts = new CancellationTokenSource();
        cts.CancelAfter(TimeSpan.FromSeconds(3)); // 設置超時時間為3秒

        var task1 = FetchDataAsync("https://api.example.com/data1", cts.Token);
        var task2 = FetchDataAsync("https://api.example.com/data2", cts.Token);

        await Task.WhenAny(task1, task2);

        if (cts.IsCancellationRequested)
        {
            Console.WriteLine("請求超時");
        }
        else
        {
            var result = await task1; // 或者 await task2,取決于哪個任務先完成
            Console.WriteLine("請求成功: " + result);
        }
    }

    static async Task<string> FetchDataAsync(string url, CancellationToken cancellationToken)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync(url, cancellationToken);
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException e)
            {
                if (e.Message.Contains("請求超時"))
                {
                    throw; // 重新拋出異常,讓調用者處理
                }
                else
                {
                    throw new Exception("獲取數(shù)據(jù)時發(fā)生錯誤", e);
                }
            }
        }
    }
}
  1. 使用Task.RunCancellationToken

你還可以使用Task.Run方法創(chuàng)建一個異步任務,并在其中使用CancellationToken來處理超時。這種方法類似于第一種方法,但將任務提交給Task.Run。

示例:

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        CancellationTokenSource cts = new CancellationTokenSource();
        cts.CancelAfter(TimeSpan.FromSeconds(3)); // 設置超時時間為3秒

        var result = await Task.Run(() => FetchDataAsync("https://api.example.com/data", cts.Token), cts.Token);

        if (cts.IsCancellationRequested)
        {
            Console.WriteLine("請求超時");
        }
        else
        {
            Console.WriteLine("請求成功: " + result);
        }
    }

    static async Task<string> FetchDataAsync(string url, CancellationToken cancellationToken)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync(url, cancellationToken);
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException e)
            {
                if (e.Message.Contains("請求超時"))
                {
                    throw; // 重新拋出異常,讓調用者處理
                }
                else
                {
                    throw new Exception("獲取數(shù)據(jù)時發(fā)生錯誤", e);
                }
            }
        }
    }
}

這兩種方法都可以用于處理C#異步開發(fā)中的超時問題。你可以根據(jù)具體需求選擇合適的方法。

0