C# 多线程编程入门攻略
本文主要介绍C#多线程编程的基础知识,包括如何创建和启动线程、锁定和解锁等常用操作。
创建和启动线程
在线程编程中,可以使用Thread类来创建和启动线程。创建Thread对象时需要传入一个ThreadStart委托对象,它指定了线程执行的入口点。
示例代码:
using System;
using System.Threading;
public class MyThread
{
public void ThreadProc()
{
Console.WriteLine("ThreadProc is running...");
}
}
public class Program
{
static void Main(string[] args)
{
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread.ThreadProc);
thread.Start(); // 启动线程
Console.WriteLine("Main thread exits...");
}
}
执行结果:
ThreadProc is running...
Main thread exits...
锁定和解锁
在多线程编程过程中,可能会遇到多个线程同时访问同一个数据资源的情况。这时候需要使用锁定和解锁机制来保证数据资源的正确性。
示例代码:
using System;
using System.Threading;
public class Counter
{
private int count;
public void Increment()
{
lock (this)
{
count++;
Console.WriteLine("{0} Incremented: {1}", Thread.CurrentThread.Name, count);
}
}
}
public class Program
{
static void Main(string[] args)
{
Counter counter = new Counter();
Thread thread1 = new Thread(() =>
{
Thread.CurrentThread.Name = "Thread1";
for (int i = 0; i < 5; i++)
{
counter.Increment();
}
});
Thread thread2 = new Thread(() =>
{
Thread.CurrentThread.Name = "Thread2";
for (int i = 0; i < 5; i++)
{
counter.Increment();
}
});
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine("Main thread exits...");
}
}
执行结果:
Thread1 Incremented: 1
Thread1 Incremented: 2
Thread2 Incremented: 3
Thread2 Incremented: 4
Thread2 Incremented: 5
Thread1 Incremented: 6
Thread1 Incremented: 7
Thread1 Incremented: 8
Thread2 Incremented: 9
Thread2 Incremented: 10
Main thread exits...
总结
本文介绍了C#多线程编程的基础知识,包括如何创建和启动线程、锁定和解锁等常用操作。在实际编程中,需要根据具体情况选择不同的线程同步机制来保证线程安全。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:c# 多线程编程 入门篇 - Python技术站