Reputation: 645
I attempt to set the value of a classes property in another thread, but the property/variable dose not obtain that value. Why is this, and how can I fix it.
Here is simple tested code demonstrating the problem
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Tests
{
class MainClass
{
static void Main()
{
ClassA alpha = new ClassA();
Console.ReadLine();
}
}
class ClassA
{
int num;
public ClassA()
{
var thread = new Thread(setNum);
thread.Start();
Console.WriteLine(num); //Why is num not 50 by this point
}
void setNum()
{
num = 50;
}
}
}
Upvotes: 1
Views: 50
Reputation: 100527
thread.Start();
Console.WriteLine(num); //Why is num not 50 by this point
For about the same reason there was no answer when you just posted the message - starting thread (on SO or in .Net/native code) does not mean that it will be immediately completed with good conclusive result.
You need to wait till completion in one way or another (i.e. check out Thread.Join
).
Upvotes: 3
Reputation: 61349
setNum
has almost definitely not been run yet. Since you started it on its own thread, the OS scheduler has to swap out your existing thread, and start running the new thread.
The chances of that happening between the instruction that starts the thread and the very next one are nearly zero.
If you need to wait for the thread to finish, Join
it so you block until its done, and consider using a different pattern like async/await
as its far less messy for situations like this.
Upvotes: 2