using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp3
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
#region One Monitor Object Test
readonly static object _Sync = new Object();
const int _total = 100000;
static long _Count = 0;
private void Button_Click(object sender, RoutedEventArgs e)
{
Task task = Task.Run(DoRrr);
for (int i = 0; i < _total; i++)
{
bool lockToken = false;
try
{
Monitor.Enter(_Sync, ref lockToken);
_Count++;
}
finally
{
if (lockToken)
Monitor.Exit(_Sync);
}
}
task.Wait();
xLabelResult.Content = _Count.ToString();
}
private void DoRrr()
{
for (int i = 0; i < _total; i++)
{
bool lockToken = false;
try
{
Monitor.Enter(_Sync, ref lockToken);
_Count--;
}
finally
{
if (lockToken)
Monitor.Exit(_Sync);
}
}
}
#endregion
#region Monitor Wait Test
//先用这个来锁定目标
private void Btn_WaitTrigger_Click(object sender, RoutedEventArgs e)
{
var task = Task.Run(() =>
{
Monitor.Enter(_Sync);
Thread.Sleep(10000);
Monitor.Exit(_Sync);
});
}
#endregion
}
// 再用这个尝试获取锁定的目标
private void Button_TryToGetIn_Click_1(object sender, RoutedEventArgs e)
{
var task = Task.Run( () =>
{
if (Monitor.TryEnter(_Sync, 20000))
{
MessageBox.Show("Get Trigger");
}
else
{
MessageBox.Show("No not get inter");
}
});
}
}
C# Monitor 锁定对象和 计时重入 的例子
最新推荐文章于 2024-09-30 06:55:35 发布
本文通过实例详细讲解了C#中Monitor类的使用,包括如何锁定对象以确保线程安全,以及如何实现计时重入锁的机制。通过对这些概念的理解和实践,读者将能够更好地掌握C#并发编程中的同步控制。
477

被折叠的 条评论
为什么被折叠?



