Reputation: 40012
I need to constantly poll a data store for possible updates. I am achieving this using the following code. This is a windows forms application by the way.
var uiContext = TaskScheduler.FromCurrentSynchronizationContext();
var updateTask = Task.Factory.StartNew(() =>
{
while (true)
{
Thread.Sleep(5000);
Task.Factory.StartNew(() =>
{
someData = dataStore.GetData();
}).ContinueWith(t =>
{
someGrid.DataSource = someData;
}, uiContext);
}
});
someData
is a private class field and someGrid
is a datagrid control.
This seems to work perfectly, but I was wondering if there is a better way of achieving it. Also, should my outer Task be LongRunning?
EDIT:
Ok, at the suggestion of Jon and Henk, I am using a Timer instead:
uiContext = TaskScheduler.FromCurrentSynchronizationContext();
updateTimer = new System.Timers.Timer(5000);
updateTimer.Elapsed += updateTimer_Elapsed;
updateTimer.Enabled = true;
The elapsed event:
void updateTimer_Elapsed(object sender, ElapsedEventArgs e)
{
someData = dataStore.GetData();
Task.Factory.StartNew(() =>
{
someGrid.DataSource = someData;
}, uiContext);
}
Upvotes: 1
Views: 1757
Reputation: 273244
Instead of Sleep()
ing in a PoolThread you could/should use a Timer.
For WinForms you can simply use the Widows.Forms.Timer.
If you do want to do it this way then Yes, use the Longrunning option. But it is still wasting a Thread.
Upvotes: 5