Reputation: 7216
Hey guys, I'm getting a really strange error. I have a program that needs to run a thread on startup, and for some reason when I do myThread.Start()
in Form1()
it will crash with "program is not working" (But only on Windows Server, not on my local machine!). However, if I put the same code under button1_Start()
it works no problem. What gives?
Any ideas? Thank you.
EDIT A little extra information: In my thread I have a line of code that uses invoke
Invoke(new Action(() => richTextBox1.AppendText(string.Format("Updating {0}..\n", DateTime.Now))));
And for some reason the crashing goes away after I make the thread sleep for 2 seconds before it starts executing. Am I using the right method to execute code on the app startup?
Upvotes: 1
Views: 594
Reputation: 7340
In our company we had the same symptom on an application that spawned a bitmap async loading that used COM - only on W2008.
The problem turned out to be:
I don't know why only on W2008, but our hack was to move the start of the thread from the constructor to the actual point where the thread work was needed.
Upvotes: 0
Reputation: 391634
Note, this is a guess, you haven't given nearly enough information in your question to give you any definitive answers.
I doubt it has anything to do with Windows Server 2008, but probably more with the fact that the server has more CPU cores and/or a faster processor than your development machine.
If you, in the thread tries to either access the form through a variable, or you try to invoke back to the thread that owns the form, you will crash on a fast computer.
Why?
In the first case, the variable has not yet been set. The following code:
var fm = new Form1();
here, fm
will not be set before the constructor has returned. If your thread has already tried to access the form through fm
, that variable is null
.
In the second case, the constructor is not responsible for showing the form, that happens afterwards. Many controls postpone actually allocating a handle until they are asked to draw themselves, and thus if the thread tries to do stuff to a control before that, it will crash.
You should instead start your thread from Form_Load
.
Upvotes: 2