我有以下代碼。多種方法的C#鎖定對象
public class AgeIncrementor
{
private static readonly object syncLock = new object();
public AgeIncrementor()
{
Age = 0;
}
public int Age { get; set; }
public void IncrementAge()
{
Task.Run(() =>
{
try
{
lock (syncLock)
{
Age += 10;
Console.WriteLine("Increased to {0}", Age);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
});
}
public void Complete()
{
Console.WriteLine("Printing from Complete() method.");
}
}
和主要方法的代碼如下:
class Program
{
static void Main(string[] args)
{
var ageIncrementor = new AgeIncrementor();
Console.WriteLine("Age is {0}", ageIncrementor.Age);
for (int i = 0; i < 5; i++)
{
ageIncrementor.IncrementAge();
}
ageIncrementor.Complete();
Console.WriteLine("Completed");
Console.WriteLine("Final Age is {0}", ageIncrementor.Age);
Console.ReadKey();
}
}
我意料的是,當我叫完成()方法和我期待的輸出如下所有線程都將完成。
Age is 0
Increased to 10
Increased to 20
Increased to 30
Increased to 40
Increased to 50
Printing from Complete() method.
Completed
Final Age is 50
但我得到如下所示的輸出。
Age is 0
Printing from Complete() method.
Completed
Final Age is 0
Increased to 10
Increased to 20
Increased to 30
Increased to 40
Increased to 50
如何確保運行IncrementAge()方法的所有線程都應該執行?
鎖只是確保在多個線程不會在同一時間進入受保護的代碼。我認爲你必須更多地等待所有的任務完成。可能會返回任務並將其存儲在數組中,然後調用['Task.WaitAll'](https://msdn.microsoft.com/en-us/library/dd270695(v = vs.110).aspx) –
我認爲你需要1)將'IncrementAge()'中的任務保存到一個成員變量中,2)等待它在'Complete()中完成 或者你可以從'IncrementAge()'返回'Task'並等待使用['Task.WaitAll'](https://msdn.microsoft.com/en-us/library/dd270695(v = vs.110).aspx) – GreatAndPowerfulOz
鎖定與執行順序無關它只是防止多重訪問。 –