【问题标题】:Delegate to other thread with parameters in C#在 C# 中使用参数委托给其他线程
【发布时间】:2012-07-24 17:13:50
【问题描述】:

如何将带参数的函数委托给 C# 中的其他线程?

如果我自己尝试,我会收到此错误:

error CS0149: Method name expected

这就是我现在拥有的:

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;
        }
    }

我想从另一个线程更新主线程中的进度条。

【问题讨论】:

    标签: c# windows multithreading


    【解决方案1】:

    您不使用参数初始化委托:

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

    相反,将这些参数传递给Invoke

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

    您还需要在委托定义中指定这些参数。但是,有一种更简单的方法,使用内置的Action<...> 代表。我还对其他代码进行了一些改进。

    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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      这不是有效的代码:

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

      请以MSDN Delegates documentation 为起点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-15
        • 2015-04-22
        • 1970-01-01
        • 2012-07-12
        • 1970-01-01
        • 1970-01-01
        • 2015-10-24
        • 1970-01-01
        相关资源
        最近更新 更多