Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variables defined in main thread in second thread?

In my C# console application, I start a new task and call a function that requires me to be able to access variables that were defined in the main thread, for example:

class Example
{
    static int ExampleVarForQuestion = 1;
    int Main()
    {
        new Task(WhereProblemOccures.ExampleFunction).Start();
    }
}

class WhereProblemOccures
{
    static int ExampleFunction()
    {
        if(Example.ExampleVarForQuestion == 1)
            return 1;
        else
            return 0;
    }
}

The problem is that the above variable value ExampleVarForQuestion is not able to be reached in ExampleVarForQuestion(). I'm quite new to C#, so if this question wasn't worded very good sorry about that.

like image 683
C0d1ng Avatar asked Mar 31 '26 08:03

C0d1ng


1 Answers

For it to be reached it must be public as your method is defined in another class.

Note that if the member is going to be written by another thread you should add some form of synchronization to guarantee thread safety.

like image 102
Slugart Avatar answered Apr 02 '26 20:04

Slugart