c# check if task is running

21,030

Solution 1

How about

Task t = Task.Run(() => ...);

if(t.Status.Equals(TaskStatus.Running))
{
    //task is running
}

Basically I would store my tasks somewhere and make them accessible for other classes. Then you can check the status of the task with the code above. Refer to the TaskStatus-Documentation.

Solution 2

This is what worked for me.

Task t = Task.Run(() => ...);

if(t.IsCompleted.Equals(false))  // or if(t.Status.Equals(TaskStatus.WaitingForActivation)
{
}
Share:
21,030
ShaneKm
Author by

ShaneKm

I am a .Net software engineer, mentor, thinker, and loud-mouth on the microservices, software architecture, and development of enterprise applications. With over 15+ years of commercial software development experience across a wide range of technologies, I’ve successfully delivered software products for embedded, Windows, and web platforms. I'm a passionate manager and developer always looking for opportunities and challenges with an approach to defining computing and network infrastructure through patterns, SOLID principles, and practices of writing clean and extensible code. In my free time, you can find me exploring the city, at the gym, or reading a book.

Updated on July 18, 2022

Comments

  • ShaneKm
    ShaneKm almost 2 years

    I need to be able to check if a specific task is running:

                Task.Run(() =>
                    {
                        int counter = 720;
                        int sleepTime = 7000;
                        int operationId = 0;
                        Thread.CurrentThread.Name = "GetTasksStatusAsync";
    ......
    

    so in my code somewhere in another class I need to check "GetTasksStatusAsync" is running. thanks

  • Kjellski
    Kjellski about 10 years
    I think this is more complete: if (t.IsCompleted == false && t.Status != TaskStatus.Running && t.Status != TaskStatus.WaitingToRun && t.Status != TaskStatus.WaitingForActivation) this prevents re-start(read start again) starting again inside the if block.
  • Eddie
    Eddie about 5 years
    I had to use an uppercase 'E' in equals, but this worked for me: t.Status.Equals(TaskStatus.Running)