多个任务同时访问和修改同一个文件或者数据的时候,由于多个任务同时修改文件或数据,就有可能导致数据出现不可预测的异常错误:
class StateObject
{
private int State = 5;
public void ChangeState()
{
if (State == 5)
{
Thread.Sleep(1);
State++;
Console.WriteLine("State: " + State + " : " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1);
}
State = 5;
}
}
static void Main(string[] args)
{
StateObject State = new StateObject();
for (int i = 0; i < 20; i++)
{
Task t = new Task(State.ChangeState);
t.Start();
}
Console.ReadKey();
}
输出结果:
State: 6 : 6
State: 7 : 10
State: 7 : 12
State: 6 : 11
State: 6 : 6
State: 6 : 12
State: 6 : 10
State: 6 : 11
State: 6 : 6
State: 6 : 12
State: 7 : 10
State: 6 : 11
State: 6 : 6
State: 6 : 10
对于这种情况,可以通过加锁来对多个任务需要访问数据进行加以限制,同一时刻只有一个任务可以访问修改数据;
class StateObject
{
private int State = 5;
Object _Lock = new object();
public void ChangeState()
{
lock (_Lock)
{
if (State == 5)
{
Thread.Sleep(1);
State++;
Console.WriteLine("State: " + State + " : " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1);
}
State = 5;
}
}
}
输出结果:
State: 6 : 11
State: 6 : 10
State: 6 : 12
State: 6 : 9
State: 6 : 11
State: 6 : 10
State: 6 : 12
State: 6 : 9
State: 6 : 11
State: 6 : 10
State: 6 : 12
State: 6 : 9
State: 6 : 11
State: 6 : 10
State: 6 : 12
State: 6 : 9
State: 6 : 11
State: 6 : 10
State: 6 : 12
State: 6 : 9