Decided to not use any timers. What i did is simpler.
Added a backgroundworker. Added a Shown event the Shown event fire after all the constructor have been loaded. In the Shown event im starting the backgroundworker async.
In the backgroundworker DoWork im doing:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while(true)
{
cpuView();
gpuView();
Thread.Sleep(1000);
}
}
I think
BackgroundWorker
is too complex thing for the case; withTimer
it is difficult to implement guaranteed stopping.I would like to recommend you using worker
Thread
with the loop which waits cancellationManualResetEvent
for the interval you need:Here is the draft version of the code. Please note I have not tested it, but it could show you the idea.
First make sure to get your head around multithreathing and it's problems (especially UI stuff).
Then you can use somethink like
Please keep in mind (just like John Koerner told you) your
cpuView()
andgpuView()
will not work as is.In my case I was using a BackgroundWorker ,a System.Timers.Timer and a ProgressBar in WinForm Application. What I came across is on second tick that I will repeat the BackgroundWorker's Do-Work I get a Cross-Thread Exception while trying to update ProgressBar in ProgressChanged of BackgroundWorker .Then I found a solution on SO @Rudedog2 https://stackoverflow.com/a/4072298/1218551 which says that When you initialize the Timers.Timer object for use with a Windows Form, you must set the SynchronizingObject property of the timer instance to be the form.
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
In this case it's better to use two
System.Threading.Timer
and execute your cpu-intensive operations in these two threads. Please note that you must access controls withBeginInvoke
. You can encapsulate those accesses into properties setter or even better pull them out to a view model class.You can't just throw this code into a background worker and expect it to work. Anything that updates UI elements (labels, textboxes, ...) needs to be invoked on the main thread. You need to break out your logic to get the data and the logic to update the UI.
I would say your best bet is to do this:
In the timer Tick() method:
In the background worker DoWork() method:
In the background worker Completed() method:
Yes you can:
In your Timer tick event:
In your Backgroundworker dowork event: