Sudha
Sudha

Reputation: 503

How to implement TPL to run a process after 1 minute delay?

I need some suggestion on the following situation. We have two APIs lets say API1 and API2. API1 calls a method from API2. Sometimes API1 unable to contact API2. But API1 used to try three times if it unable to contact API2. After three times, still if API1 unable to contact API2, we decided to add 1 minute delay and try again. API1 should not depends on this 1 minute delayed process result. It should return a response to the user like 'please check email for result'. For this, we tried

TPL(Task Parallel Library)

While using TPL, the API1 waits to complete the task and then only it returns the result.

Threading

We tried thread pool but it is old fashioned.

.NET Framework 4.0

Here the code for API1 implements TPL

 public string TestTPL()
    {
        string str = string.Empty;
        int i = 1;
        ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
        while (i <= 3)
        {
            //call a method resides in API2
            string str = obj.API2Method();
            if (string.IsNullOrEmpty(str))
                i++;
            else
                break;
        }
        if (string.IsNullOrEmpty(str))
            Parallel.Invoke(() => DoSomeWork());
        return "Hey, I came";
    }

    public void DoSomeWork()
    {
        //wait for 1 min
        System.Threading.Thread.Sleep(60000);
        ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
        //call a method resides in API2
        string str = obj.API2Method();
       //send mail to the user 

    }

Upvotes: 2

Views: 406

Answers (3)

Sudha
Sudha

Reputation: 503

To run a child task independent of parent method, we can use Task class.

   public string TestTPL()    //parent method
    {
        Task task = new Task(DoSomeWork);  //child task
        task.Start();
        return "Hey, I came";
    }

Tasks can get their own dedicated thread and do not consume a thread from the pool. In case of Parallel.Invoke, parent method wait until the child task get finished.

Upvotes: 2

zenith
zenith

Reputation: 186

Task.Wait(60000).Run( () => {

} );

Upvotes: 0

Negative Eddy
Negative Eddy

Reputation: 401

Parallel.Invoke() is a synchronous call which means it will not return until all of its children are complete. In this case it will wait until DoSomWork() is done.

Instead of

if (string.IsNullOrEmpty(str))
            Parallel.Invoke(() => DoSomeWork());

Try something like

if (string.IsNullOrEmpty(str))
             Task.Run(() => DoSomeWork());

That will return immediately and execute DoSomeWork() on a thread from the thread pool.

The threadpool is old but its still a good tool. The TPL just gives you some better semantics to express what work being done at a higher level rather than how it is being done underneath the covers.

Upvotes: 0

Related Questions