【问题标题】:C# thread does not set variable value of another class?C#线程不设置另一个类的变量值?
【发布时间】:2018-02-04 01:16:32
【问题描述】:

这是我的测试代码:

  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”值。 看起来 Thread 确实设置了值,但是当从 main 方法中检索 testV 值时,它什么也没给出。 这是为什么呢?

【问题讨论】:

  • 从主线程读取可能发生在其他线程有机会写入值之前

标签: c# c#-4.0 c#-3.0


【解决方案1】:

无法保证在您的主线程调用WriteLine 时已经设置了Global.test。要查看效果,可以先睡一会儿再写出来,以证明其他线程修改了它。

另外,值得注意的是,全局静态 testV 不是线程安全的,因此未来会有未定义的行为。

【讨论】:

【解决方案2】:

在您的特定情况下,Console.WriteLine(Global.test);runThread 运行得更早。最简单的方法是使用Join

var thread = new Thread(delegate() { runThread(); }).Start();
thread.Join();

Console.WriteLine(Global.test);

但这绝对不适用于生产代码(手动线程创建也是如此)。

【讨论】:

    猜你喜欢
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多