简体   繁体   中英

Cannot Interlocked.Exchange object except for types already declared in its overloads

I'm testing with threads for my project. While testing, I realizes that we cannot assign variable in threads. After that I found a solution: using Interlocked class.

I tested it with int , it works really well. But as soon as I change it to a class, it throws me:

NullReferenceException: Object reference not set to an instance of an object.

I was expecting a line with "Class" in the output.

Can anyone explain me what is going on here?

Code (assuming that the code is in the Program class and every namespace needed is declared):

static Class i;

static void Main(string[] args)
{
    Thread thread = new Thread(new ThreadStart(ModThread));
    thread.Start();

    Console.WriteLine(i.ToString());
    Console.ReadKey();
}

static void ModThread ()
{
    Interlocked.Exchange(ref i, new Class());
}

class Class { }

Primitive values are never null. They have some default value.

Classes that have not been initialized can be null. So in this line

Interlocked.Exchange(ref i, new Class());

Your ref is null because i is not initialized here: static Class i;

Try your code with static Class i = new Class();

Check documentation here: https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked.exchange?view=netframework-4.8

public static object Exchange (ref object location1, object value);

Exceptions ArgumentNullException The address of location1 is a null pointer.

Edit 1

To see the updated value, make the main thread sleep for a bit and then print the outcome.

    thread.Start();
    Thread.Sleep(100);

You can't control the execution order when you are using threads. So what happens is:

  1. The second thread is told to start
  2. The first thread prints the current value
  3. The second thread copies the value

With the Sleep command, we tell the first thread to wait a bit so the second one is able to change the value before the first one WriteLine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM