Currently I am working on an application, developed with C#. I have a question pertaining to Tasks. I have done my research on the topic of Tasks and asynchronous programming. But I am still not completely confident while working with tasks.
This application has a method namely ReadOrWriteDBTable. This method carries out either a read or a insert operation on a SQL table every second. Basically this method will be called every second. Currently this method is running on the same thread as that of the GUI thread of the application. In the beginning this is not a problem because very less data will be present in the table, but as the data quantity increases in the table, it can bring many problems on the GUI. Therefore I would like to carry out these Database operations in a different thread from that of the GUI thread.
This means that, every second the method ReadOrWriteDBTable should be called via a new thread. This brings in multi threading and I believe it gets difficult to manage the threadpool. What I understood from TASKS is that all the complex operations of multiple threading is handled completely by a TASK. So I have handled the above problem of multiple threading with Tasks in the following way.
public int PollingTrigger
{
get
{
return this.pollingTrigger;
}
set
{
this.pollingTrigger = value;
Task.Factory.StartNew(ReadOrWriteDBTable);
}
}
Public void ReadOrWriteDBTable()
{
// Database select and update….
}
The PollingTrigger property is called every second and in turn a new task is created for the method ReadOrWriteDBTable(). Since I do not need results to be returned from the task, I do not use the Async and the await keyword for the task and do not want any asynchronous operations to be carried out. I would like to know, is this usage of Tasks correct and safe from exceptions? Will this help me to initiate a new thread , whenever a new value is set to the property PollingTrigger (In this application every second)?
I am sorry for such a detailed explanation. I just wanted to make my question clear. I hope it’s clear . Looking forward for your tips or answers!
You don't have to go
Taskroute. I'm not sure if notawait-ing (or.Wait) on an outstanding task leaks resources or not (I think they're meant to be accounted for, but not sure), but you can simply useTimerclass that will use one of ThreadPool threads to run arbitrary function on a set interval, which is exactly what you want. Easier to manage. There are several Timers that .NET provides, see description in the link for differentiation.