我以前从未在C#中使用线程,我需要有两个线程,以及主UI线程.基本上,我有以下几点.
public void StartTheActions()
{
//Starting thread 1....
Thread t1 = new Thread(new ThreadStart(action1));
t1.Start();
// Now, I want for the main thread (which is calling `StartTheActions` method)
// to wait for `t1` to finish. I've created an event in `action1` for this.
// The I wish `t2` to start...
Thread t2 = new Thread(new ThreadStart(action2));
t2.Start();
}
Run Code Online (Sandbox Code Playgroud)
所以,基本上,我的问题是如何让一个线程等待另一个线程完成.做这个的最好方式是什么?
何时在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)
更新
谢谢大家的帮助:我发布了另一个问题,作为您提供的一些信息的后续跟进.由于您似乎精通这一领域,我发布了链接:此锁定和管理锁定异常的解决方案有什么问题?
我想这是一个有趣的代码示例.
我们有一个类 - 让我们称之为Test - 使用Finalize方法.在Main方法中有两个代码块,我使用lock语句和Monitor.Enter()调用.另外,我在这里有两个Test类的实例.实验非常简单:将Lock变量置于锁定块内,然后尝试使用GC.Collect方法调用手动收集它.因此,要查看Finalize调用,我将调用GC.WaitForPendingFinalizers方法.正如你所看到的,一切都很简单.
通过lock语句的定义,编译器将其打开到try {...} finally {..}块,并在try块和Monitor内部调用Monitor.Enter.然后它在finally块中退出.我试图手动实现try-finally块.
在两种情况下我都期望相同的行为 - 使用锁和使用Monitor.Enter.但是,令人惊讶的是,它有所不同,如下所示:
public class Test
{
private string name;
public Test(string name)
{
this.name = name;
}
~Test()
{
Console.WriteLine(string.Format("Finalizing class name {0}.", name));
}
}
class Program
{
static void Main(string[] args)
{
var test1 = …Run Code Online (Sandbox Code Playgroud) 有没有办法测试当前线程是否在对象上持有监视器锁定?即相当于Java中的Thread.holdsLock.
谢谢,