Reputation: 7005
I generally set up repeating tasks, like GUI updates, etc like this:
MonitorTimer = new System.Threading.Timer(new TimerCallback(Monitor), null, 1000, 2000);
I have recently started starting tasks now with
Task.Factory.StartNew(() =>
{
MyApp();
});
What is the preferred approach to creating a repeated task now? I can't see any obvious options to do this with StartNew.
Upvotes: 1
Views: 244
Reputation: 117027
I prefer to use Microsoft's Reactive Framework. Then I can do this:
var subscription =
Observable
.Interval(TimeSpan.FromSeconds(1.0))
.ObserveOn(this) /* this is the current form */
.Subscribe(() =>
{
MyApp();
});
This handles all the UI thread marshalling, the timing, and the invocation of the method.
You can easily cancel it like this:
subscription.Dispose();
Upvotes: 2
Reputation: 5042
Keep using System.Threading.Timer. Alternatively, you can use Wait to wait for an event in a dedicated thread, but there are little good reasons for it I can think of.
Upvotes: 0