Akshay Vats
Akshay Vats

Reputation: 170

Check/Solve cross thread operation

There is a StatusProgressBar, which is often accessed from threads. To ensure this, its Text property is as follow:-

[Browsable(true)]
    public override string Text
    {
        get
        {
            return prg.Text ;
        }
        set
        {


            prg.Text = value;

        }
    }

And the prg.Text = value looks like this

public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {

            Misc.CrossThread(this , delegate
        {

            base.Text = value;
        }, true);
        }

public static void CrossThread(Control control, MethodInvoker d, bool forceSynchronous)
    {

        if (control.InvokeRequired)
        {
            if (forceSynchronous)
            {
                control.Invoke((Action)delegate { CrossThread(control, d, forceSynchronous); });
            }
            else
            {
                control.BeginInvoke((Action)delegate { CrossThread(control, d, forceSynchronous); });
            }
        }
        else
        {
            if (control.IsDisposed)
            {
                throw new ObjectDisposedException("Control is already disposed.");
            }

            d();
        }

    }

Now the problem is, when its accessed from UI thread (sometimes), the text doesn't change.. ex.

if (cbGateway.SelectedIndex == -1) 
    { bp.Text = "Select GATEWAY"; return; }

here 'bp' refers to StatusProgressBar object.

Now if I put a breakpoint at

{ bp.Text = "Select GATEWAY"; return; }

and then continue, everything happens as expected, text changes.. Why the text isn't changed first time?

Upvotes: 1

Views: 334

Answers (2)

Otiel
Otiel

Reputation: 18743

Did you try doing the following in your CrossThread method?

Application.DoEvents();

Upvotes: 0

Fischermaen
Fischermaen

Reputation: 12458

If you access the progressbar from the UI thread during a long running task, the progressbar will be not refreshed until that long running task is finished.

Upvotes: 1

Related Questions