Ian Cordle
Ian Cordle

Reputation: 206

How do I create a variable that a different thread can use? (C#)

I am new to C#, so please try to be basic and explain things as much as possible.

This is my code right now:

using System;
using System.Threading;
class MathQuiz
{
  static void Main() 
  {
    Thread ask = new Thread (new ThreadStart (prompt));

    ask.Start();
    Console.ReadKey();
  }

  static void prompt()
  {
    Console.WriteLine ("Testing!");
  }
}

What I want to do, however, is have the new thread read a ConsoleKeyInfo to an object. Then, if the user doesn't press a key in 10 seconds, they move on to the next question, which repeats the process with a different answer.

Hopefully, you're still with me.

I need to have a variable in the MAIN thread be modifiable and callable in the "prompt" thread.

How can I do this?

Upvotes: 0

Views: 5424

Answers (3)

Rob
Rob

Reputation: 27357

The thread will still have access to the variables you've defined in the same class. The prompt function won't have access because you've defined it as static. Create a static variable, and pass the function to ThreadStart as MathQuiz.prompt

Also, be aware of locking on variables

To the comment below, they are shared across threads:

void Main() 
{
    a.doit();
}

public class a
{
      private static int i = 1;
      public static void doit()
      {
        Thread ask = new Thread (new ThreadStart (prompt));

        ask.Start();
        Console.WriteLine(i);
        Console.Read();
        Console.WriteLine(i);
      }

    static void prompt()
    {
        Console.WriteLine ("Testing!");
        a.i++;
    }
}

Upvotes: 1

SLaks
SLaks

Reputation: 887195

You can make a static field in your class.

Alternatively, you can pass an anonymous delegate to the thread constructor; it will be able to access local variables.

In either case, it should also be volatile.

Upvotes: 2

beastofman
beastofman

Reputation: 1361

Mark it as static volatile so threads can access it without creating class's instance and modify it and use the same value across all threads.

Upvotes: 5

Related Questions