Home > OS >  Asynchronous function that run in a given time interval in c# visual studio
Asynchronous function that run in a given time interval in c# visual studio

Time:03-11

In my visual studio, windows application project I have a function getSensorApiData() which is used to retrieve data and saving to database. I want to run this function in every given seconds to update data without affecting other running functions in the project. I used the following code.

      Task.Factory.StartNew(() =>
        {
            System.Threading.Thread.Sleep(3000);
            getSensorApiData();
        });

But when I use this code some other functions in the project not working properly. Help me to solve this problem..

CodePudding user response:

try:

static void Main(string[] args)
{
    var timer = new Timer(Callback, null, 0, 3000);

    //Dispose the timer
    timer.Dispose();
}
static void Callback(object? state)
{
    //Your code here.
    _=DoAsync();
}
private async Task DoAsync()
{
    await getSensorApiData();
}
    

CodePudding user response:

This exact solution I needed a while back.

I execute the method in a new thread and control the delay inside the method being called.

This how I seperated its execution in independent thread without disturbing the rest of code.

new Thread(async () => await bnb.GetDataset()).Start();

And this is how I make sure it is being called at specific intervals i.e 1 sec.

public async Task GetDataset()
{
  while (true)
  {
    //your code...
    await Task.Delay(1000);
  } 
}
  • Related