I want do define an action that sets a property with a value (calculated by a worker thread). That action should be called in another thread context (UI thread).
To simplify the problem – it boils down to the question: why does this code don’t work and what do I have to do to make it work like intended:
public struct Person
{
public string Name;
}
Person person;
Action<Person> action;
public void Update()
{
person = new Person();
new Thread(() =>
{
action = new Action<Person>(c => c.Name = "Me");
}).Start();
Thread.Sleep(1000);
action(person);
Debug.WriteLine(person.Name ?? "null");
}
Why is this giving me “null” instead of “Sami”?
The type
Personis a struct. This means that when you passpersonas an argument, a copy is made. So the action updates a copy, a notpersonitself. If you changePersonto a class, you will see that your example works.For more information about the difference between structs and classes, see what’s the difference between struct and class in .Net?