c#

.net和c#如何实现并发编程

小樊
85
2024-11-28 14:51:53
栏目: 编程语言

在.NET和C#中实现并发编程,可以使用多种方法。以下是一些常用的技术和模式:

1. 任务并行库(TPL)

任务并行库(TPL)是.NET框架的一部分,提供了Task类和相关的API,用于并行和异步编程。

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        await Task.WhenAll(DoWorkAsync("Task1"), DoWorkAsync("Task2"), DoWorkAsync("Task3"));
    }

    static async Task DoWorkAsync(string taskName)
    {
        Console.WriteLine($"{taskName} started.");
        await Task.Delay(1000); // 模拟耗时操作
        Console.WriteLine($"{taskName} completed.");
    }
}

2. 并行LINQ(PLINQ)

并行LINQ允许你以并行方式执行LINQ查询。

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        var result = numbers.AsParallel()
                             .Where(n => n % 2 == 0)
                             .ToList();

        Console.WriteLine("Even numbers:");
        foreach (var number in result)
        {
            Console.WriteLine(number);
        }
    }
}

3. 异步编程模式(APM)

异步编程模式(APM)使用BeginXXXEndXXX方法来执行异步操作。

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

class Program
{
    static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            var response = await client.GetAsync("https://api.example.com/data");
            var data = await response.Content.ReadAsStringAsync();
            Console.WriteLine(data);
        }
    }
}

4. 并发集合

.NET提供了并发集合类,如ConcurrentQueueConcurrentDictionary等,用于在多线程环境中安全地操作集合。

using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

class Program
{
    static ConcurrentQueue<int> queue = new ConcurrentQueue<int>();

    static void Main()
    {
        Task producer = ProduceAsync();
        Task consumer = ConsumeAsync();

        Task.WaitAll(producer, consumer);
    }

    static async Task ProduceAsync()
    {
        for (int i = 0; i < 10; i++)
        {
            queue.Enqueue(i);
            Console.WriteLine($"Produced: {i}");
            await Task.Delay(100);
        }
    }

    static async Task ConsumeAsync()
    {
        while (queue.TryDequeue(out int item))
        {
            Console.WriteLine($"Consumed: {item}");
            await Task.Delay(200);
        }
    }
}

5. 锁和同步块

使用lock关键字或Monitor类来保护共享资源。

using System;
using System.Threading;

class Program
{
    private static readonly object lockObject = new object();
    private static int sharedResource = 0;

    static void Main()
    {
        Thread t1 = new Thread(() => IncrementResource());
        Thread t2 = new Thread(() => IncrementResource());

        t1.Start();
        t2.Start();

        t1.Join();
        t2.Join();

        Console.WriteLine($"Final value: {sharedResource}");
    }

    static void IncrementResource()
    {
        lock (lockObject)
        {
            sharedResource++;
            Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} incremented: {sharedResource}");
        }
    }
}

6. 使用asyncawait

在方法中使用asyncawait关键字来简化异步编程。

using System;
using System.Threading.Tasks;

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

    static async Task DoWorkAsync()
    {
        Console.WriteLine("Started.");
        await Task.Delay(1000); // 模拟耗时操作
        Console.WriteLine("Completed.");
    }
}

这些技术和模式可以帮助你在.NET和C#中实现高效的并发编程。根据具体的需求和场景,可以选择合适的方法来处理并发问题。

0
看了该问题的人还看了