I'm trying to update form.text from a thread. Basically thread need to update the form.text with the current time. my code looks like below
UpdateText("My Monitor (Last Updated " + DateTime.Now.ToString("HH:mm:ss tt") + ")", Form1.ActiveForm);
and the method as below
void UpdateText(String s, Control c)
{
if (c.InvokeRequired)
{
this.BeginInvoke(new MethodInvoker(() => UpdateText(s, c)));
}
else
{
c.Text = s;
}
}
As long as the main application window is active, code works. If the application becomes inactive, then I get the error "Object reference not set to an instance of an object"
You are calling Form1.ActiveForm
.
ActiveForm : A Form that represents the currently active form, or null if there is no active form.
If the Form
is inactive, naturally this would be null
. Use a different reference to your form. If you are calling it from within the form, use this
.
Keep the reference of ActiveForm
in a private field, and use that field in the Thread
Control activeControl;
private void start_new_thread()
{
active = Form1.ActiveForm;
// start work under thread
}
private void work_under_thread(object state)
{
//blocking works
// update here
UpdateText("My Monitor (Last Updated " + DateTime.Now.ToString("HH:mm:ss tt") + ")", activeControl);
}
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.