简体   繁体   中英

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. 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. I tried using threads, but then they can't update the 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. 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.

Put following code in your background call where UI update is required. UI just needs to invoked from its own thread.

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

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