偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

C#實(shí)現(xiàn)異步編程的常用方式總結(jié)

開發(fā) 前端
異步編程是現(xiàn)代軟件開發(fā)中不可或缺的一部分,尤其是在處理耗時(shí)操作時(shí)。C#提供了多種實(shí)現(xiàn)異步編程的方式,包括使用async和await關(guān)鍵字、Task類、基于委托的異步方法、基于IAsyncEnumerable的異步數(shù)據(jù)流以及基于TPL Dataflow的異步數(shù)據(jù)流處理。

異步編程是現(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)目的具體需求選擇合適的方式。

責(zé)任編輯:武曉燕 來源: 程序員編程日記
相關(guān)推薦

2015-09-16 15:11:58

C#異步編程

2021-10-12 17:47:22

C# TAP異步

2019-05-16 13:00:18

異步編程JavaScript回調(diào)函數(shù)

2009-09-09 13:31:15

C# TextBox

2009-08-20 17:30:56

C#異步編程模式

2009-08-20 17:47:54

C#異步編程模式

2012-07-27 10:02:39

C#

2009-07-31 18:28:46

實(shí)現(xiàn)C#顯示圖像

2009-08-21 10:13:02

C#異步初步

2009-08-21 09:20:44

C#異步套接字

2022-07-01 08:00:44

異步編程FutureTask

2009-08-26 09:48:48

C#異步套接字

2016-12-14 15:05:08

C#異步編程

2025-04-30 01:50:00

C#異步編程

2021-08-02 11:13:28

人工智能機(jī)器學(xué)習(xí)技術(shù)

2009-08-20 16:33:44

Socket異步通訊

2009-08-21 11:24:16

C#異步調(diào)用

2009-08-21 10:17:14

C#異步網(wǎng)絡(luò)編程

2009-08-25 11:10:20

C#編程實(shí)現(xiàn)顯示XML

2024-12-20 09:48:47

C#Python代碼
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)