1

I have a windows service running in background which do some task at every 15 minutes, but I have to call a function with multiple time like in a loop and execution for one time of that function can also take more than 15 minutes depends on configuration. Any suggestion for that like fire and forget for achieving this.

CallTask is function called in Service every 15 minutes.

Sometimes StartTask gets executed some time not, also sometimes its getting executed only one time only.

public void CallTask()
{
    try
    {
        DataTable dt = getdata(); 

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            Task.Run(() => StartTask(Convert.ToString(dt.Rows[i]["PackageId"])));
        }
    }
    catch (Exception ex)
    {
        //throw;
    }
}

public async Task StartTask(string PackageId)
{
    int timegap = 30 * 1000;
    //module 1
    int Slice1 = 10;
    for (int i = 0; i < Slice1; i++)
    {
        // this is api call which needs to be called at every 30 seconds,
        // for number of slices which can vary.
        var _response = await CallApi(PackageId); 

        SaveResultinDB(_response);

        await Task.Delay(timegap);
    }
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Hardik
  • 21
  • 3
  • Have you tried adding a `try`/`catch` block inside the `StartTask` method, and logging the errors? – Theodor Zoulias May 20 '22 at 16:54
  • @TheodorZoulias yes , no error was found , most of the times it is executing function only one time , not all iteration of loop. – Hardik May 24 '22 at 12:09
  • You should also do error handling inside the lambda that you pass to the `Task.Run`: `Task.Run(() => { try { ... } catch { ... } });`. My guess is that your problem is related to this issue: [Captured variable in a loop in C#](https://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp). – Theodor Zoulias May 24 '22 at 12:25
  • Btw launching operations in a fire-and-forget manner is [frowned upon](https://stackoverflow.com/questions/36335345/web-api-fire-and-forget) by the experts, but I guess that you have good reasons for doing it. – Theodor Zoulias May 24 '22 at 12:29
  • @TheodorZoulias thanks for suggestion , I add lock in logging method which was adding log in txt file and now working fine – Hardik May 25 '22 at 11:32

0 Answers0