Introduction
We often come across a scenario where we need to run some function for a long time where this function will react on some trigger and then run some code logic. This is where we need to apply a long running task. This task stays active and responds to a specific trigger. In today’s article we will look at creating such a long running task. We will pass to it the function that needs to run and when the trigger is activated a single run of the function will be executed.
The Long Running Task
In this example, we have created a class as below,
- using System;
- using System.Threading;
- using System.Threading.Tasks;
- namespace LongRunningTask
- {
- public class LongTask
- {
- readonly CancellationTokenSource cts = new CancellationTokenSource();
- readonly AutoResetEvent are = new AutoResetEvent(false);
- public async Task StartTask(int value, Func<int,Task> act)
- {
- while (true)
- {
- if (cts.IsCancellationRequested) throw new OperationCanceledException();
- await act(value);
- are.WaitOne();
- value++;
- }
- }
- public void NextStep()
- {
- are.Set();
- }
- public void CancelTask()
- {
- cts.Cancel();
- }
- }
- }
In this class, we see that we have a function called Start Task which accepts some initial value that will be used by the executing function. The second parameter is the function itself. This function has an input type of integer (which we are using only as an example here) and the return type of a task. If we will be running a self-isolated task that returns no values, we can simply use an Action delegate as well. We then start an endless loop and do the following steps inside it,
- Add a cancellation check in case we want to cancel the long running task
- Execute the function
- Block further execution using an AutoResetEvent primitive
Now, when we start the task, the passed function will execute once and stop until a signal is received via the “NextStep” function to continue. Once this signal is received, we will call the Set function on the AutoResetEvent primitive and run the function one more time. In this example, we simply increment the input integer value by one. In a real-life scenario, inputs can be updated based on requirements. Also, we have another function called “CancelTask”. When called, we use a CancellationTokenSource to cancel the task.
Example of using the Long Running Task
For demonstration purposes, I have created a Windows Form .NET Core 3.1 application. This application has three labels we will use to start the task, run the next step in the loop and finally cancel the task. For some strange reason, it seems that buttons are missing from the toolbar and hence I decided to use labels. Below is the layout and code for the application,



Alan ChenPosted Jun 11, 2021, 6:55 PM
I am new to C#. Can you tell me how to change the function in StartTask? In other words, for example, instead of calling LongRunningTask every time when the NextSteop is invoked, I'd like to run a different function, like LongRunningTask1, LongRunningTask2, etc.
Graeme AllwoodPosted Aug 17, 2020, 6:08 PM
Hi Munib... Thanks for the great article. We are looking to create an application that will use long running tasks that will cancel themselves if specific conditions are met. I assume we can use this code and then call the "public void CancelTask()" (i.e. CancelTask()) within the LongTask class.