下面是我的测试代码:
class Program
{
static void Main(string[] args)
{
new Thread(delegate() { runThread(); }).Start();
Console.WriteLine(Global.test);
Console.ReadKey();
}
private static void runThread()
{
Console.WriteLine("this is run thread");
Global.test = "this is test from thread";
Console.WriteLine(Global.test);
}
}
public class Global
{
public static string testV { get; set; }
}我希望能够使用线程设置"testV“值。看起来线程确实设置了值,但是当从testV方法中检索main值时,它没有给出任何值。为什么会这样呢?
发布于 2013-05-30 15:28:53
不能保证在主线程调用WriteLine时已经设置了Global.test。要查看效果,您可以尝试在写出它之前休眠一小段时间,以证明另一个线程已经修改了它。
此外,值得注意的是,全局静态testV不是线程安全的,因此未定义的行为将在您的未来。
https://stackoverflow.com/questions/16830335
复制相似问题