• 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

    • LG gram Book 15U50T: Is this lightweight laptop the right upgrade for you? by Paul Hill If you’re in the UK looking for a new mid-range laptop that won’t feel underpowered, check out the LG gram Book 15U50T now because it’s at its all-time lowest price on Amazon UK thanks to a 14% discount from its £699.99 RRP. You can get it now for just £599.99 (Buying link at the end). At this price, the laptop definitely makes this mid-range option much more appealing, it’s also pretty new having only come out in January 2025, so you’re definitely getting more value for your money. The delivery is free and will take a few days to arrive unless you take advantage of a Prime member trial and get it next-day in time for Father’s Day. LG gram Book 15U50T: Key features and who it's for The LG gram Book 15U50T features a 15.6-inch Full-HD (1920x1080) anti-glare IPS display, making it ideal for use in well-lit areas as you won’t see yourself staring back. It’s powered by an Intel Core i5 processor (1334U), 16GB of RAM, and has a very fast 512GB NVMe Gen4 SSD. In my opinion, the storage might be a bit tight for some users; however, the device comes with two M.2 slots if you want to upgrade the storage. The LG gram Book 15U50T is ideal for students or professionals who need a device to carry with them out and about. It has an ultra-lightweight design and weighs just 1.65kg - that’s not too far off a similarly sized MacBook Air, but for a fraction of the cost. In terms of ports, there is an HDMI port, two USB-A ports, and two USB-C ports. There's also a 3.5mm headphone jack if you need to plug in headphones. Other noteworthy details about this laptop include that it's running Windows 11 Home with Copilot integration, it has a HD webcam with a privacy shutter, it uses Dolby Atmos audio for immersive sound, and it has a unique feature called gram Link for multi-device (including Android and iOS) connectivity. Should you buy it? If you are a student or a professional that won’t be doing heavy gaming, or using other super intensive applications, this laptop is a solid pick. It’s lightweight - so easy to carry around, it has an anti-reflective screen - so good in well-lit environments; and it features upgradeable storage slots if 512GB is not enough space. On the downside, this laptop has a mid-range processor that could limit your ability to use high-end professional tools. Another thing I’m not really a fan of here is how opaque LG has been with the battery life. As a portable laptop, you’re obviously going to want to take it on the go where you don’t have a charger handy, but all LG says about the battery is that it has a capacity of 51Wh. According to some online sources, variants of this laptop manage about 7 to 10 hours, so if you need a super long battery life, you might be better off with something like a MacBook Air. So should you buy it? If you’re not going to be doing anything super intensive, but can’t stand underpowered and slow budget laptops then this could be the ideal laptop for you. The £100 discount makes it even more appealing! LG gram Book 15U50T: £599.99 (Amazon UK) / RRP £699.99 This Amazon deal is U.K. specific, and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon UK deals page here. Get Prime, Prime Video, Music Unlimited, Audible or Kindle Unlimited, free for the first 30 days As an Amazon Associate we earn from qualifying purchases.
    • Totally different vehicles. Uber has partnered with Waymo for level 5 autonomous vehicles. Waymo has completed 10 million trips and to date, there have been 696 accidents in 4 years and of those 16 of them appear to have been due to an error by the car. In total airbags have only been deployed 38 times. The technology should always be under review and continued to be improved on, but this is a totally different animal to Tesla FSD PS. no I don't work for them etc. I am an analyst for a market intelligence firm and we have a lot of interest from clients looking at the connected car space for advertising etc. so I have studied them
    • But it's not full self driving it's level 2 autonomy. Audi, BMW and Mercedes all have level 3 and make far less noise about it
    • Edge for Business gets secure password deployment for organizations by Paul Hill Microsoft Edge for Business now offers organizations secure password deployments as a generally available feature, the Redmond giant said. Instead of users sharing passwords on sticky notes or via email to access certain websites or tools, admins can deploy encrypted shared passwords to specific users within their organization. When a user receives a password, it is stored in their Edge password manager and can be used to log into websites seamlessly using autofill. Microsoft has made this enterprise-grade solution available to customers at no additional cost. How it works and the user experience Administrators have to manage the feature via the Microsoft Edge management service within the Microsoft 365 admin center. From there, they can add, update, and revoke credentials for specific user groups through configuration policies. Once an admin has set it up and shared passwords with users, the users will see the passwords in their Edge password manager and can be used with autofill on corresponding websites. The passwords are tied to work profiles in Edge on managed Windows devices to limit their misuse. Further boosting security, the shared passwords cannot actually be viewed, edited, or deleted (unless the website allows), or exported from the password manager. This is a good addition for security because if an unauthorized user gains physical access to the computer, they cannot learn what the password is. Administrators reading this do need to be aware of an important caveat related to developer tools. A motivated user who wants to reveal the passwords can do so by digging into the developer tools, for this reason, you should consider restricting access to the developer tools by configuring the DeveloperToolsAvailability policy. The underlying security and encryption Microsoft’s new secure passwords feature has been built using the Information Protection SDK. The passwords are encrypted and the encryption is tied to Entra identities which lets organizations enforce them without manual key management. The decryption of the passwords takes place at runtime using the same SDK, validating the user’s identity. Availability and getting started Secure password deployment is available through the Edge management service in the Microsoft 365 admin center. Once in the admin center, you should choose an existing configuration policy or create a new one. Inside the policy, go to the Customization Settings tab and then to the Secure password deployment page. To use this feature you must have a Microsoft 365 Business Premium, E3, or E5 subscription. The feature also requires the Edge admin or Global admin role. Source: Microsoft
    • Is it though?  I built a new rig a few months ago and it was literally impossible to get one without RGB, but within 10 minutes of setting it up, I turned all that crap off.  It was REALLY distracting, and who needs additional heat INSIDE a PC? It's popular on YouTube for sure, it's neat looking and whatnot, but it's about as practical as a coffee cup with a hole in it. As for the price, a non-enthusiast would just see something priced way above what they can get from a retailer brand new...
  • Recent Achievements

    • Week One Done
      somar86 earned a badge
      Week One Done
    • One Month Later
      somar86 earned a badge
      One Month Later
    • Apprentice
      Adrian Williams went up a rank
      Apprentice
    • Reacting Well
      BashOrgRu earned a badge
      Reacting Well
    • Collaborator
      CHUNWEI earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      504
    2. 2
      ATLien_0
      260
    3. 3
      +Edouard
      187
    4. 4
      +FloatingFatMan
      175
    5. 5
      snowy owl
      132
  • Tell a friend

    Love Neowin? Tell a friend!