何时在C#中使用Monitor类或lock关键字来确保线程安全?
编辑:
到目前为止,答案似乎lock是对Monitor课程的一系列调用的简写.锁定电话到底是什么?或者更明确地说,
class LockVsMonitor
{
private readonly object LockObject = new object();
public void DoThreadSafeSomethingWithLock(Action action)
{
lock (LockObject)
{
action.Invoke();
}
}
public void DoThreadSafeSomethingWithMonitor(Action action)
{
// What goes here ?
}
}
Run Code Online (Sandbox Code Playgroud)
更新
谢谢大家的帮助:我发布了另一个问题,作为您提供的一些信息的后续跟进.由于您似乎精通这一领域,我发布了链接:此锁定和管理锁定异常的解决方案有什么问题?
在C#中访问bool字段原子?特别是,我需要锁定:
class Foo
{
private bool _bar;
//... in some function on any thread (or many threads)
_bar = true;
//... same for a read
if (_bar) { ... }
}
Run Code Online (Sandbox Code Playgroud) 我有理解困难时期 Wait(),Pulse(),PulseAll().他们都会避免僵局吗?如果您解释如何使用它们,我将不胜感激?
我正在寻找一种方法来重新启动已被Abort()停止的线程.
public partial class MyProgram : Form
{
private Thread MyThread = new Thread(MyFunction);
private System.Windows.Forms.Button startStopBtn = new System.Windows.Forms.Button();
public MyProgram()
{
MyThread.Start();
startStopBtn += new EventHandler(doStop);
startStopBtn.Text = "Stop";
}
private static void MyFunction()
{
// do something
}
private void doStop(object sender, EventArgs e)
{
MyThread.Abort();
startStopBtn -= new EventHandler(doStop);
startStopBtn += new EventHandler(doStart);
startStopBtn.Text = "Start";
}
private void doStart(object sender, EventArgs e)
{
MyThread.Start(); // << Error returned when clicking the button for 2nd time …Run Code Online (Sandbox Code Playgroud)