开发者

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

开发者 https://www.devze.com 2023-02-05 18:31 出处:网络
I am new to C#, so please try to be basic and explain things as much as possible. This is my code right now:

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 ThreadStar开发者_C百科t (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?


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消