
モニターとロックはどちらも、オブジェクト アクセスを同期するためのメカニズムを提供します。
lock は Monitor.Enter と try のショートカットです。
ロックはショートカットであり、基本的な使用方法のオプションです。さらに制御が必要な場合は、TryEnter()、Wait()、Pulse()、および高度なマルチスレッド ソリューション用の & を使用してください。
PulseAll() メソッドの場合は、Montior クラスを選択します。
ロックの例 -
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Program{
static object _lock = new object();
static int Total;
public static void Main(){
AddOneHundredLock();
Console.ReadLine();
}
public static void AddOneHundredLock(){
for (int i = 1; i <= 100; i++){
lock (_lock){
Total++;
}
}
}
|
ログイン後にコピー
モニターの例−
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Program{
static object _lock = new object();
static int Total;
public static void Main(){
AddOneHundredMonitor();
Console.ReadLine();
}
public static void AddOneHundredMonitor(){
for (int i = 1; i <= 100; i++){
Monitor.Enter(_lock);
try {
Total++;
}
finally{
Monitor. Exit (_lock);
}
}
}
}
|
ログイン後にコピー
以上がC# の Monitor と Lock の違いは何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。