Vincent Ducroquet Vincent Ducroquet -4 years ago 463
C# Question

How to check task status in c#

I'd like to know how can i check status of an asynchronous task in c#.
I have a save method to save users, and i'd like to run a background task to update them after the save.

I'm in framework 4.0, here is my code to begin the task

System.Threading.Tasks.Task task = null;
task = System.Threading.Tasks.Task.Factory.StartNew(() =>
{
beginTask();
});


My problem is the task take some times to end (near 7 mins) so if someone do several user saves, the task is runned several times, so i'd like to check before running the task if the function beginTask() is already running to avoid to have a lot of background tasks are running.

Thanks

Answer Source

I think I found better solution. Check if it suits you.

public class TaskDemo
{
    private static AutoResetEvent autoReset = new AutoResetEvent(true);

    Action beginTask = () =>
    {
        Console.WriteLine("Method start");
        Thread.Sleep(2000);
    };

    public void RunTask()
    {
        Task myTask = Task.Run(() =>
            {
                autoReset.WaitOne();
                beginTask();
            }).ContinueWith(t => autoReset.Set());
    }
}

And simply console app test:

static void Main(string[] args)
    {
        TaskDemo td = new TaskDemo();
        // Simulation multiple requests 
        Thread.Sleep(1000);
        td.RunTask();
        Thread.Sleep(1000);
        td.RunTask();
        Thread.Sleep(1000);
        td.RunTask();
        Thread.Sleep(1000);
        td.RunTask();
        Thread.Sleep(1000);
        td.RunTask();
        Thread.Sleep(1000);
        td.RunTask();
    }

The clue is to use bool taskRunning to signal task state and

Task myTask = Task.Factory.StartNew(() =>
                {
                    taskRunning = true;
                    beginTask();
                }).ContinueWith((t) => taskRunning = false);

to change its state during run and after finish (ContinueWith((t) => taskRunning = false)).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download