Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / C#

Improper Usage of Invoke

Rate me:
Please Sign up or sign in to vote.
3.14/5 (14 votes)
26 Jun 2006CPOL4 min read 52.3K   232   20  
Asynchronous programming is great, but improper use can cause your form to become non-responsive.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //  Invoke does not work without the control
            //  handle first being created.  Since I am 
            //  starting the worker threads in the constructor, 
            //  I have to force creation of this handle early.
            //  Remove this code and see what happens!
            while (!IsHandleCreated)
            {
                // force handle creation
                IntPtr temp = Handle;
            }
            ThreadPool.QueueUserWorkItem(Foo);
            ThreadPool.QueueUserWorkItem(Foo);
            ThreadPool.QueueUserWorkItem(Foo);
        }
        public void Foo(object o)
        {
            while (true)
            {
                rtb.Invoke(new StringDelegate(UpdateDisplay), 
                    new object[] { "Foo!\n" });
                //Thread.Sleep(10);
            }
        }
        public void UpdateDisplay(string text)
        {
            this.rtb.Text += text;
        }

        public delegate void StringDelegate(string foo);
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Will Sullivan is a full time C# programmer in Columbia, SC. He enjoys sticking his finger through his right nostril and out his left tear duct. In photoshop.

Comments and Discussions