C#實(shí)現(xiàn)異步編程的常用方式總結(jié)
異步編程是現(xiàn)代軟件開發(fā)中不可或缺的一部分,尤其是在處理耗時(shí)操作時(shí)。C#作為一種功能強(qiáng)大的編程語言,提供了多種實(shí)現(xiàn)異步編程的方式。本文將介紹C#中常用的五種異步編程方式,并附上示例代碼。
1. 使用async和await關(guān)鍵字
C# 5.0引入了async和await關(guān)鍵字,極大地簡(jiǎn)化了異步編程。使用async標(biāo)記的方法可以在不阻塞主線程的情況下執(zhí)行異步操作,而await關(guān)鍵字則用于等待一個(gè)Task完成。
using System;
using System.Threading.Tasks;
public class AsyncExample
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine("調(diào)用異步方法前");
        string result = await GetDataAsync("https://example.com/data");
        Console.WriteLine("調(diào)用異步方法后");
        Console.WriteLine(result);
    }
    public static async Task<string> GetDataAsync(string url)
    {
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }
    }
}2. 使用Task類
Task類是.NET Framework 4.0引入的,用于表示一個(gè)異步操作。Task.Run方法是一個(gè)常用的方式來啟動(dòng)一個(gè)后臺(tái)任務(wù)。
using System;
using System.Threading.Tasks;
public class TaskExample
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine("主線程,線程ID: " + Thread.CurrentThread.ManagedThreadId);
        Task task1 = new Task(() => TaskFunc1());
        task1.Start();
        
        var result = Task.Run<string>(() => { return TaskFunc2(); });
        Console.WriteLine(result.Result);
    }
    private static void TaskFunc1()
    {
        Console.WriteLine("Task方式一開啟的線程ID: " + Thread.CurrentThread.ManagedThreadId);
    }
    private static string TaskFunc2()
    {
        return "Task方式二開啟的線程ID: " + Thread.CurrentThread.ManagedThreadId;
    }
}3. 基于委托的異步方法
在委托類型中定義BeginInvoke()和EndInvoke()兩個(gè)方法,可以實(shí)現(xiàn)異步編程。
using System;
using System.Threading;
public class DelegateAsyncExample
{
    public static void Main(string[] args)
    {
        Console.WriteLine("調(diào)用異步方法前");
        string param = "參數(shù)";
        PostAsync(param);
        Console.WriteLine("調(diào)用異步方法后");
        Console.ReadKey();
    }
    private delegate void AsyncFoo(string param);
    private static void PostAsync(object param)
    {
        AsyncFoo caller = Myfunc;
        caller.BeginInvoke(param.ToString(), FooCallBack, caller);
    }
    private static void FooCallBack(IAsyncResult ar)
    {
        var caller = (AsyncFoo)ar.AsyncState;
        caller.EndInvoke(ar);
    }
    private static void Myfunc(string param)
    {
        Console.WriteLine("通過委托來實(shí)現(xiàn)異步編程的");
    }
}4. 基于IAsyncEnumerable的異步數(shù)據(jù)流
IAsyncEnumerable是.NET Core 2.0引入的,提供了一種異步枚舉大量數(shù)據(jù)的方式。
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class AsyncStreamExample
{
    public static async Task Main(string[] args)
    {
        await foreach (var item in GetLargeDataAsync())
        {
            Console.WriteLine(item);
        }
    }
    public static async IAsyncEnumerable<int> GetLargeDataAsync()
    {
        for (int i = 0; i < 10; i++)
        {
            await Task.Delay(1000); // 模擬異步操作
            yield return i;
        }
    }
}5. 基于TPL Dataflow的異步數(shù)據(jù)流處理
TPL Dataflow(Task Parallel Library Dataflow)提供了多種塊(如BufferBlock、TransformBlock<T, T>等),可以組合起來構(gòu)建數(shù)據(jù)處理管道。
using System;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
public class DataflowExample
{
    public static async Task Main(string[] args)
    {
        var buffer = new BufferBlock<int>();
        var processor = new TransformBlock<int, string>(async x => await ProcessAsync(x));
        buffer.LinkTo(processor);
        buffer.Post(1);
        buffer.Post(2);
        buffer.Complete();
        await processor.Completion;
    }
    private static async Task<string> ProcessAsync(int x)
    {
        await Task.Delay(1000); // 模擬異步操作
        return "Processed: " + x;
    }
}結(jié)論
異步編程是現(xiàn)代軟件開發(fā)中不可或缺的一部分,尤其是在處理耗時(shí)操作時(shí)。C#提供了多種實(shí)現(xiàn)異步編程的方式,包括使用async和await關(guān)鍵字、Task類、基于委托的異步方法、基于IAsyncEnumerable的異步數(shù)據(jù)流以及基于TPL Dataflow的異步數(shù)據(jù)流處理。每種方式都有其適用場(chǎng)景和優(yōu)勢(shì),開發(fā)者可以根據(jù)項(xiàng)目的具體需求選擇合適的方式。















 
 
 



 
 
 
 