Library code snippets

UI Threading Helper Classes

Introduction

One of the most cumbersome things you will ever have to do with Winforms is updating your User interface while receiving events from another thread. For example, you have a long-running method, but you want to show a progress bar while it runs. To make the application responsive during execution of this method, you decide to run the method in a new Thread. No problems! However, you can't just call methods on the progress bar control from the running method. The reason lies in the fact that the Progress bar is part of the Form thread, which is different from the Method thread. Calling methods on another thread can lead to application hangs and other great stuff.

The only way to call methods on the progress bar control is by calling the Form.Invoke() method, which takes a delegate to a method which would perform this operation. Form.Invoke() performs the invocations using the Form's thread, which is the "good" way to perform these operations.

This means that every time you want to update your UI from another thread, you'd need to create 2 separate methods and 2 separate delegates. One method and delegate to recieve the event from the thread which then " Invoke "s another delegate to a method on the form, whcih actually updates the UI. Agh . Isn't that wonderful?

Comments

  1. 23 Mar 2005 at 11:29
    i am an fresh graduate.i need a suggestion abt how to use threading in dcom application.


    how to reduce the loading time.


    then my final one is, how to run a 2 different threads in DCOM application.

    plz friends any one suggest me.

    its my request.

    regards,
    fresh bee
  2. 01 Jan 1999 at 00:00

    This thread is for discussions of UI Threading Helper Classes.

Leave a comment

Sign in or Join us (it's free).

Roy Osherove Roy Osherove has spent the past 6+ years developing data driven applications for various companies in Israel. He's acquired several MCP titles, written a number of articles on various .NET topics, ...

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

We'd love to hear what you think! Submit ideas or give us feedback