简体   繁体   中英

Make a c# application that runs continuously

I am writing a client side app that pushes data from users computers up to a website. I want this application to update the website every 60ish seconds. Right now I have my function wrapped in an infinite while loop with a 45 second sleep. But, windows says the application is not responding even though its updating the website. Here is how my code is structured.

Your problem is that your while loop is blocking the UI thread . To fix this, you need to run your code on a separate thread.

The easiest way to do this to start off.. might be to use a Timer :

System.Timers.Timer timer = new System.Timers.Timer(45000); // timer will execute every 45 seconds

timer.Elapsed += (sender, e) => {
    // your upload code here
};

timer.Start();

You should definitely look into Threading at a later stage though. Perhaps a BackgroundWorker or the Task Parallel Library.

Thread.Sleep(...) blocks the UI thread for the number of specified milliseconds. One approach is to use Task.Delay(..) to not block the UI thread, but rather wait 45 seconds concurrently:

private async void button1_Click(object sender, EventArgs e)
{
    running = true;

    while (running)
    {
        //your code

        await System.Threading.Tasks.Task.Delay(4500);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM