Laurence
Laurence

Reputation: 1875

Delegate to other thread with parameters in C#

How can you delegate a function with parameters to an other thread in C#?

If I try it on my own I get this error:

error CS0149: Method name expected

This is what I have now:

delegate void BarUpdateDelegate();
    private void UpdateBar(int Value,int Maximum,ProgressBar Bar)
    {
        if (Bar.InvokeRequired)
        {
            BarUpdateDelegate Delegation = new BarUpdateDelegate(Value, Maximum, Bar); //error CS0149: Method name expected
            Bar.Invoke(Delegation);
            return;
        }
        else
        {
            Bar.Maximum = Maximum;
            Bar.Value = Value;

            //Insert the percentage
            int Percent = (int)(((double)Value / (double)Bar.Maximum) * 100);
            Bar.CreateGraphics().DrawString(Percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(Bar.Width / 2 - 10, Bar.Height / 2 - 7));

            return;
        }
    }

I want to update from an other thread the progress bar in the main thread.

Upvotes: 1

Views: 546

Answers (2)

Ry-
Ry-

Reputation: 225238

You don't initialize a delegate with arguments:

BarUpdateDelegate Delegation = new BarUpdateDelegate(Value, Maximum, Bar); //error CS0149: Method name expected
Bar.Invoke(Delegation);

Instead, pass those arguments to Invoke.

BarUpdateDelegate delegation = new BarUpdateDelegate(UpdateBar);
Bar.Invoke(delegation, Value, Maximum, Bar);

You'll also need to specify those arguments in your delegate definition. However, there is an easier way, using the built-in Action<...> delegates. I also made a couple other code improvements.

private void UpdateBar(int value, int maximum, ProgressBar bar)
{
    if (bar.InvokeRequired)
    {
        bar.Invoke(new Action<int, int, ProgressBar>(UpdateBar),
                   value, maximum, bar);
    }
    else
    {
        bar.Maximum = maximum;
        bar.Value = value;

        // Insert the percentage
        int percent = value * 100 / maximum;
        bar.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", 8.25f, FontStyle.Regular), Brushes.Black, bar.Width / 2 - 10, bar.Height / 2 - 7);
    }
}

Upvotes: 3

Tim S.
Tim S.

Reputation: 56576

This is not valid code:

BarUpdateDelegate Delegation = new BarUpdateDelegate(Value, Maximum, Bar);

Please see the MSDN Delegates documentation as a starting point.

Upvotes: 0

Related Questions