0

here is my testing code:

  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; }
}

I want to be able to set "testV" value with a thread. it looks like Thread does set value, but when retrieving testV value from main method, it gives nothing. why is that?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1225072
  • 335
  • 1
  • 4
  • 11
  • 1
    The reading from the main thread probably occurs before the other thread had a chance to write the value – vc 74 May 30 '13 at 07:28

2 Answers2

4

There is no guarantee that that Global.test has been set by the time your main thread calls WriteLine. To see the effects, you could try sleeping for a little bit before writing it out, to prove the other thread has modified it.

Also, it's worth noting that the global static testV is not thread-safe and so undefined behaviour is in your future.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
1

In your particular case Console.WriteLine(Global.test); runs earlier, than runThread. The simplest way is to use Join:

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

Console.WriteLine(Global.test);

But this is not for production code, definitely (then same is true for manual thread creation too).

Dennis
  • 37,026
  • 10
  • 82
  • 150