T
tendaimare
Guest
I have a task thats doing some work in my form and I call it in the form load like so
bool isRunning = false;
Stopwatch timeOutWatchA = new Stopwatch();
private void Form1_Load(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
if (Settings.CurrentSettings.EnableA)
WeightReadingThreadA();
});
}
private void WeightReadingThreadA()
{
SerialPort portA = new SerialPort();
TimeOutA();
timeOutWatchA.Start();
try
{
portA.Open();
if (portA.IsOpen)
{
while (isRunning)
{
//Does something here
this.Invoke(new Action(() =>
{
try
{
//display results to UI
}
catch (Exception)
{
}
}));
timeOutWatchA.Reset();
timeOutWatchA.Start();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void TimeOutA()
{
Task.Factory.StartNew(() =>
{
while (isRunning)
{
Thread.Sleep(1000);
if ((timeOutWatchA.ElapsedMilliseconds / 1000) > 3)
{
this.Invoke(new Action(() =>
{
try
{
//display message to UI
//This is where Iam getting
//the error when I try to
//close the form
}
catch (Exception)
{
}
}));
}
}
});
}
private void BtnClose_Click(object sender, EventArgs e)
{
isRunning = false;
this.Close();
}
When I try and close the form I get the error "'Invoke or BeginInvoke cannot be called on a control until the window handle has been created". My question is how can i stop this error so i can close the form nicely. I have tried setting the variable isRunning to false before I close the form but this is not working
If you think it you can achieve it
Continue reading...
bool isRunning = false;
Stopwatch timeOutWatchA = new Stopwatch();
private void Form1_Load(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
if (Settings.CurrentSettings.EnableA)
WeightReadingThreadA();
});
}
private void WeightReadingThreadA()
{
SerialPort portA = new SerialPort();
TimeOutA();
timeOutWatchA.Start();
try
{
portA.Open();
if (portA.IsOpen)
{
while (isRunning)
{
//Does something here
this.Invoke(new Action(() =>
{
try
{
//display results to UI
}
catch (Exception)
{
}
}));
timeOutWatchA.Reset();
timeOutWatchA.Start();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void TimeOutA()
{
Task.Factory.StartNew(() =>
{
while (isRunning)
{
Thread.Sleep(1000);
if ((timeOutWatchA.ElapsedMilliseconds / 1000) > 3)
{
this.Invoke(new Action(() =>
{
try
{
//display message to UI
//This is where Iam getting
//the error when I try to
//close the form
}
catch (Exception)
{
}
}));
}
}
});
}
private void BtnClose_Click(object sender, EventArgs e)
{
isRunning = false;
this.Close();
}
When I try and close the form I get the error "'Invoke or BeginInvoke cannot be called on a control until the window handle has been created". My question is how can i stop this error so i can close the form nicely. I have tried setting the variable isRunning to false before I close the form but this is not working
If you think it you can achieve it
Continue reading...