如何在 C# 中将带参数的函数委托(delegate)给另一个线程?
如果我自己尝试,我会得到这个错误:
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;
}
}
我想从其他线程更新主线程中的进度条。
最佳答案
您不使用参数初始化委托(delegate):
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);
您还需要在委托(delegate)定义中指定这些参数。但是,有一种更简单的方法,使用内置的 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);
}
}
关于c# - 在C#中使用参数委托(delegate)给其他线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11635940/