C#线程


C#是一种面向对象的编程语言,它提供了一些强大的多线程编程特性,可以帮助开发者在应用程序中实现并发处理和异步操作。


线程概念

C#中的线程是指一条独立的执行路径,程序可以在多个线程之间切换执行,从而实现并发处理。C#中的线程由System.Threading.Thread类来表示,可以通过创建Thread对象来启动一个新的线程。


线程知识点

1.创建新线程:可以通过创建Thread对象,并使用Start()方法来启动一个新线程。

2.线程同步:在多线程应用程序中,需要使用锁、信号量等机制来控制多个线程之间的同步和协作。

3.线程池:线程池可以提供一组可重用的线程,可以帮助应用程序管理线程的数量,从而提高应用程序的性能和响应速度。

4.异步编程:C#提供了异步编程模型(async/await),可以在不阻塞主线程的情况下执行耗时操作,并在操作完成时返回结果。

5.取消线程:可以使用CancellationToken对象来取消线程的执行,从而提高程序的可靠性和健壮性。


示例代码

以下是一些C#多线程编程的示例代码:

1.创建新线程

using System;
using System.Threading;
class Program {
    static void Main(string[] args) {
        Thread t = new Thread(new ThreadStart(DoWork));
        t.Start();
    }
    static void DoWork() {
        // 新线程执行的代码
        Console.WriteLine("New thread started.");
    }
}

2.线程同步

using System;
using System.Threading;
class Program {
    static int count = 0;
    static object lockObject = new object();
    static void Main(string[] args) {
        Thread t1 = new Thread(new ThreadStart(IncrementCount));
        Thread t2 = new Thread(new ThreadStart(IncrementCount));
        t1.Start();
        t2.Start();
        t1.Join();
        t2.Join();
        Console.WriteLine("Count: " + count);
    }
    static void IncrementCount() {
        for (int i = 0; i < 100000; i++) {
            lock (lockObject) { //使用Lock锁住引用对象让其他线程等待防止并发
                count++;
            }
        }
    }
}

3.线程池

using System;
using System.Threading;
class Program {
    static void Main(string[] args) {
        for (int i = 0; i < 10; i++) {
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), i);
        }
        Console.ReadLine();
    }
    static void DoWork(object state) {
        int i = (int)state;
        Console.WriteLine("Working on item " + i);
        Thread.Sleep(1000);
        Console.WriteLine("Finished item " + i);
    }
}

4.异步编程

异步操作则不会阻塞当前线程。相反,它会在单独的线程中执行,同时允许控制流返回到调用方,使得调用方可以继续执行其他任务。当异步操作完成后,它会将结果返回给调用方,或者通过回调或事件通知调用方。

using System;
using System.Threading.Tasks;
class Program {
    static async Task Main(string[] args) {
        Console.WriteLine("Starting work...");
        string result = await DoWorkAsync();
        Console.WriteLine("Result: " + result);
    }
    static async Task<string> DoWorkAsync() {
        await Task.Delay(1000);
        return "Finished work.";
    }
}

取消线程

using System;
using System.Threading;
class Program {
    static void Main(string[] args) {
        CancellationTokenSource cts = new CancellationTokenSource();
        Thread t = new Thread(new ThreadStart(() => {
            while (!cts.IsCancellationRequested) {
                Console.WriteLine("Working...");
                Thread.Sleep(1000);
            }
            Console.WriteLine("Cancelled.");
        }));
        t.Start();
        Console.ReadLine();
        cts.Cancel();
    }
}

注意:以上代码仅供参考,实际使用中需要根据具体的场景进行修改和调整。


果糖网