Usage of tasks to initiate a new thread in C# programming

106 Views Asked by At

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!

3

There are 3 best solutions below

2
LB2 On

You don't have to go Task route. I'm not sure if not await-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 use Timer class 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.

1
Ivan Ičin On

To strictly answer your question, this does not guarantee that you will have a new thread. Task can be executed on any thread in the thread pool, it is not guaranteed to be a new one.

However this will ensure that the operation doesn't run on UI thread which is as far as I can understand what you actually wanted to ask to. Though it might not be elegant or most efficient (not sure why you need that integer), but it will work, could be good enough or maybe even very good as I don't have an insight in the rest of the project.

2
Jorge Omar Medra On

As @Ivan Ičin says using Task is not warranty that you get a new Thread. You can use QueueUserWorkItem to get an available thread from Thread Pool, if there is no available threads it will wait for one:

QueueUserWorkItem(ReadOrWriteDBTable);

But, if you are looking for improving performance in your program you must use async and await instead of Task or Thread because they (Threads) can block the I/O operations, like sockets, and you optimize the resources.

UPDATE (12 Jun): Acording with MSDN:

Asynchrony is essential for activities that are potentially blocking, such as when your application accesses the web. Access to a web resource sometimes is slow or delayed.

This information could be readed in this link: https://msdn.microsoft.com/es-mx/library/hh191443(v=vs.110).aspx

And, in your case and keep talking of async and await, this document talks about using async with UI:

When you use asynchronous methods, the application continues to respond to the UI. You can resize or minimize a window, for example, or you can close the application if you don't want to wait for it to finish.

So, as you want, using async methods help you to implements the behaivor that you are looking for yout UI but when you use the await operator, with an async method, it will make wait the thread until the async method has been ended.