简体   繁体   English

制作可连续运行的ac#应用程序

[英]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. 我希望该应用程序每60秒钟更新一次网站。 Right now I have my function wrapped in an infinite while loop with a 45 second sleep. 现在,我将函数封装在45秒的无限while循环中。 But, windows says the application is not responding even though its updating the website. 但是,Windows表示即使更新网站,该应用程序也没有响应。 Here is how my code is structured. 这是我的代码的结构。

Your problem is that your while loop is blocking the UI thread . 您的问题是while循环阻塞了UI线程 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 : 最简单的方法来开始..可能是使用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. 也许是BackgroundWorker或任务并行库。

Thread.Sleep(...) blocks the UI thread for the number of specified milliseconds. Thread.Sleep(...)将UI线程阻止指定的毫秒数。 One approach is to use Task.Delay(..) to not block the UI thread, but rather wait 45 seconds concurrently: 一种方法是使用Task.Delay(..)不阻塞UI线程,而是同时等待45秒:

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

    while (running)
    {
        //your code

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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