简体   繁体   English

线程与后台工作人员与计时器-在C#中更新UI

[英]Thread vs Backgroundworker vs Timer - Updating UI in C#

I am trying to create a time clock for clocking in and out in C# with windows forms. 我正在尝试创建一个时钟,使用Windows窗体在C#中进出。 I would like to have the current time displayed on the screen constantly. 我想将当前时间持续显示在屏幕上。 I also want to be able to ping the bosses wifi on his or her phone, then use that to determine if they are in the building. 我还希望能够在他或她的电话上ping老板无线,然后用它来确定他们是否在建筑物中。 I tried using threads, but then they can't update the UI. 我尝试使用线程,但是后来他们无法更新UI。 I also tried using timers, but it was super laggy. 我也尝试过使用计时器,但这太慢了。 I also tried a background worker, but I think that you can't update the UI with a background worker. 我也尝试了后台工作者,但是我认为您不能使用后台工作者来更新UI。 I would like to be able to update the time every second, and check if the boss is there every minute or so. 我希望能够每秒更新一次时间,并每隔一分钟左右检查一下老板是否在那里。 Please help me find a way to do this without slowing everything down. 请帮助我找到一种方法,同时又不减慢一切。

You can actually do many things from background call, updating UI is simplest. 实际上,您可以从后台调用中做很多事情,更新UI最简单。

Put following code in your background call where UI update is required. 将以下代码放在需要UI更新的后台调用中。 UI just needs to invoked from its own thread. UI仅需要从其自己的线程中调用。

this.Invoke((MethodInvoker)delegate {
                                    LabelStatus.Text = "Yeah its working";
                                    Label2.Text = "Updated UI";
                                    // do your stuff on UI thread
                                    });

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

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