• 0

[C#] Updating a label in real-time without deadlocking form


Question

I have a while loop that updates the form, while the actual information for the form is updated in a separate thread. The problem is, it is designed like this currently:

		while (!quit) {
			this.SuspendLayout();
			this.BeginInvoke(new InvokeDelegate(UpdateForm));
			System.Threading.Thread.Sleep(1000);
			this.Update();
			this.ResumeLayout(true);
		}

UpdateForm just updates the Text properties of 2 labels and exits. I've tried a lot in the past few hours, but this while loop thing has got me... How do I prevent such a deadlock? I've tried various combinations of Threads, Invoke, BeginInvoke, and the like, and nothing has worked. I've went through several tutorials on the topics (all of which dealt with the console), and understood how things worked. I even created my own console app based on what I learned. Windows Forms is a completely different animal from console apps though... Can anybody help or provide suggestions? Note that this isn't homework (I can't imagine doing this for homework...); it is just being done in the pursuit of knowledge! :)

4 answers to this question

Recommended Posts

  • 0

Here, I am assuming the child thread is doing some job X.

The BeginInvoke code, should be called from within the child thread context, and not from within the main thread (which handles the UI). You don't need a while loop in the main thread to update the UI.

edit---

Something like this:

public class ThreadExample : Form {
	// The ThreadProc method is called when the thread starts.
	// It loops ten times, writing to the console and yielding 
	// the rest of its time slice each time, and then ends.
	public void ThreadProc() {
		for (int i = 0; i < 10; i++) {
			Console.WriteLine("ThreadProc: {0}", i);
			// Yield the rest of the time slice.
			Thread.Sleep(0);
			// do job X
			this.BeginInvoke(new InvokeDelegate(UpdateForm)); // update UI
		}
	}

	private void UpdateForm() {
	  // do form updating here
	}

	public ThreadExample() {
		Thread t = new Thread(new ThreadStart(ThreadProc));
		t.Start();
	}
}

Edited by g0wg
  • 0

Thanks, g0wg. After some manipulation, I was able to adapt it to my form. All of my ideas centered around using the main thread to update the UI while having a worker thread do its job that the UI relies on. You made it simple to understand - call BeginInvoke on the separate thread to update the UI, not the main thread. Thank you very much! :)

  • 0
  rpgfan said:
Thanks, g0wg. After some manipulation, I was able to adapt it to my form. All of my ideas centered around using the main thread to update the UI while having a worker thread do its job that the UI relies on. You made it simple to understand - call BeginInvoke on the separate thread to update the UI, not the main thread. Thank you very much! :)

You should probably learn why your previous attempt failed, too.

The Invoke() and BeginInvoke() methods work by posting a message to the UI thread of the control you call it on (the thread that owns the window and contains its message loop). Since you're calling this function from the UI thread, that message is sitting in the message queue for the thread you're currently running on. And since you are blocking that thread with your loop, its message loop will never be called and the message telling it to invoke your UpdateForm command will never be processed. In fact, you're just going to sit there filling up the message queue forever.

If you're new to Windows or UI programming, you should take the time to learn how windows (not Windows the OS, but "windows" the programming concept) work. Understanding window messages / window processes may not strictly be necessary for simple .NET programming, but it can certainly help prevent mistakes like this one.

  • 0
  Brandon Live said:
You should probably learn why your previous attempt failed, too.

The Invoke() and BeginInvoke() methods work by posting a message to the UI thread of the control you call it on (the thread that owns the window and contains its message loop). Since you're calling this function from the UI thread, that message is sitting in the message queue for the thread you're currently running on. And since you are blocking that thread with your loop, its message loop will never be called and the message telling it to invoke your UpdateForm command will never be processed. In fact, you're just going to sit there filling up the message queue forever.

If you're new to Windows or UI programming, you should take the time to learn how windows (not Windows the OS, but "windows" the programming concept) work. Understanding window messages / window processes may not strictly be necessary for simple .NET programming, but it can certainly help prevent mistakes like this one.

Thanks for the explanation, Brandon. Actually, I'm pretty decent at event-driven programming. I just wasn't thinking in an event-driven manner. I was doing too much object-oriented thinking (<sarcasm>because OOP solves all problems, right?</sarcasm> :)) and not enough intelligent thinking to realize that I was missing something so obvious. I am indeed new to UI programming, and that is probably another major reason why I didn't get it. I'm glad it was something fairly simple to resolve. Again, thanks to all that helped.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • PDF24 Creator 11.27.0 by Razvan Serea PDF24 PDF Creator installs a virtual printer driver that allows you to convert any printable document or image into PDF format. You can also import documents from your scanner, combine multiple documents into one and delete selected pages from existing PDF files. The program supports creation of secure, digitally signed documents, PDF quality settings, integrated preview, emailing, and more. You can either drag'n drop documents onto the GUI or convert them from any other program by using the virtual printer driver - simply select the PDF24 printer instead of your regular paper printer. Advantages of PDF24 PDF Creator: Once installed, create PDF files forever Free upgrades included Conversion is simple and possible from all current programs Freeware Create PDF files from almost any application Easy to use Multilingual Several features of PDF24 PDF Creator: Merge and split PDF Extract pages from a PDF Copy pages from one PDF to another PDF Integrated preview for easy PDF editing Secure a PDF (Prevent from unauthorised opening, printing, etc.) Set PDF information such as author and title The following tools are included in the new PDF Toolbox of PDF24 Creator 11: Merge PDF Compress PDF Edit PDF Convert files to pdf Convert PDF files to other formats PDF to Text PDF to HTML PDF to JPG PDF to PNG PDF to PDF, PDF/A-1, PDF/A-2, PDF/A-3 PDF to Word PDF to PowerPoint PDF to Excel Protect PDF Unlock PDF Split PDF Rotate PDF pages Delete PDF pages Extract PDF pages Sort PDF pages Create a PDF from images Convert a PDF to images Extract images from PDFs Create online application as PDF Optimize PDF for the Web Insert watermark into a PDF Insert page numbers into a PDF Overlay PDF files Compare PDF files Sign PDF files Annotate PDF files Blacken PDF files Crop PDF Flatten PDF Download: PDF24 Creator 11.27.0 | MSI Setup | ~400.0 MB (Freeware) View: PDF24 Creator Homepage | Release Notes | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Driver Genius 25.0.0.122 by Razvan Serea Driver Genius is a professional driver management tool features both driver management and hardware diagnostics. Driver Genius provides such practical functions as driver backup, restoration, update and removal for computer users. If you often reinstall your operating system, you may not forget such painful experiences of searching all around for all kinds of drivers. If unfortunately you have lost your driver CD, the search will be more troublesome and time-consuming. Driver Genius can automatically find drivers for a device when the system can't find a driver for it. It can recognize the name and vendor's information of the device, and directly provide download URL for the required driver. Driver Genius also supports online updates for drivers of existing hardware devices. Driver Genius customers can obtain information for latest drivers by Driver Genius's LiveUpdate program, which can synchronize to the database on Driver Genius site. Features at a glance: Find the latest drivers for your computer. One click to update all drivers silently. Automatically install driver updates silently. Make your drivers are always up to date. New rollback driver design for safer driver update. Free to backup all drivers now! Package all drivers to an executable auto installer. One click to restore all drivers. Remove invalid or useless drivers/devices, improve system performance and stability. New system information tool. Detailed hardware inventory. Hardware temperature monitor. Protect your CPU, GPU and HDD. New system transfer assistant. Upgrade/degrade your windows system easily. New SSD Speeder. Improve your disk performance and reliability. New System booster provides over 90 optimization options that make your computer run faster and smoother. New System Cleanup can help you to clean up the temporary files and cache files or other junk files in system. Driver Genius 25.0.0.122 changelog: Optimize driver update detection. Optimize outdated driver detection. Download: Driver Genius 25.0.0.122 | 20.4 MB (Shareware) View: Driver Genius Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Tailscale is a VPN. The cloudflared service is a reverse proxy into Cloudflares network so you can run anything through it without opening ports.
    • Clean Space 711 by Razvan Serea Clean Space is a system optimization, privacy, and cleaning tool. With this program, you can free up valuable hard disk space by removing unused files from your system, thereby allowing Windows OS to run faster and more efficiently. The program also cleans traces of your online activities, such as cookie files, and your internet history, even in third-party programs. Clean Space key features: Removes junk files (temporary files, logs, caches, cookies, etc.) Protects user privacy by deleting activity traces One-click cleanup functionality Warns about browser cloud sync risks Supports cleaning of Microsoft Store apps Enhanced cleaning for Chrome, Firefox, and other browsers Uses secure deletion methods (military-grade) Frequently updated with new features and app support Customizable cleaning zones and app selection Provides detailed cleaning reports Fast scanning and cleanup performance Compatible with Windows 7, 8/8.1, 10, and 11 Low system resource usage Priority support available in professional version Clean Space 711 changelog: Adding settings panel and new functions New Settings Section A new Settings button has been added to the main screen, giving you quick access to the app's configuration. While the current options are limited, we'll expand them based on users feedback. New function: Always Run as Administrator Now available in Settings, this feature lets you launch the app with administrative privileges by default, unlocking access to more cleanup zones on your PC. New function: Manage Ignore List By default, the app skips files which are "in-use" and unavailable for deletion. But you can disable this in Settings (not recommended). If left enabled, the ignore list resets every 24 hours, meaning previously locked files will be retried for deletion until successful deleted. New function: Startup Cache Toggle You can now disable the startup cache, which stores a list of supported zones from previous run, to speed up app our app. Bug fixes Fixed an issue where the "Update Later" button was incorrectly restricted to the Professional version - it's now available to all users. Download: Clean Space 711 | 280 KB (Free, paid upgrade available) Link: Clean Space Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • So, in other words, people who don't like the amount of telemetry included with Windows 11 can now stay with Windows 10 if they agree to copy all their data to Microsoft's cloud. You can't make this stuff up :-)
  • Recent Achievements

    • Week One Done
      DrRonSr earned a badge
      Week One Done
    • Week One Done
      Sharon dixon earned a badge
      Week One Done
    • Dedicated
      Parallax Abstraction earned a badge
      Dedicated
    • First Post
      956400 earned a badge
      First Post
    • Week One Done
      davidfegan earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      604
    2. 2
      ATLien_0
      226
    3. 3
      Michael Scrip
      167
    4. 4
      +FloatingFatMan
      154
    5. 5
      Som
      136
  • Tell a friend

    Love Neowin? Tell a friend!