Showing posts with label Task. Show all posts
Showing posts with label Task. Show all posts

Friday, January 13, 2023

How to cancel any running task by wait for sometime in C#

 Problem Statement: In some real time scenario, you may need to cancel some long running tasks in certain time interval and then proceed. 

Here in below example, i am calling some infinite time method and am not sure when it will be completed. So i am making 30 seconds maximum to wait and cancelling it. 

RunSomeTestJob();

 

string RunSomeTestJob()

{

    string result = "";

 

    //loop your logic

 

    try

    {

        Console.WriteLine("Running Job Started " + DateTime.Now.ToString());

        // Create CancellationTokenSource.

        var source = new CancellationTokenSource();

        // ... Get Token from source.

        var token = source.Token;

 

        var someTask = Task.Run(() =>

        {

            result = infinteJobWork(token);

 

        }, token);

 

        someTask.Wait(30 * 1000);

       //someTask.Dispose();

        source.Cancel();

 

    }

    catch (Exception ex)

    {

        //suppress error and proceed

        //log somewhere

    }

    Console.Write("Running Job Completed " + result + DateTime.Now.ToString());

 

    Console.Read();

 

    //proceed with next steps

 

    return result;

 

}

 

string infinteJobWork(CancellationToken token)

{

    //Short running Job - Fixed timing

    //for (int i = 0; i < 3; i++)

    {

        //Long running Job - Indefinite time

        while (true)

        {

            //TODO: make some api call or some work to external api

            Console.WriteLine("Running Job : " + DateTime.Now.ToString());

            Thread.Sleep(5 * 1000);

 

            // See if we are canceled from our CancellationTokenSource.

            if (token.IsCancellationRequested)

            {

                Console.WriteLine("Job cancelled");

                return "Job cancelled";

            }

        }

    }

    //return "Job done";

}