使用 BeginInvoke() 时出现 ArgumentException 和 TargetParameterCountException。
1) 在第一次调用时,它给出 System.ArgumentException:“System.String”类型的对象无法转换为“System.Object[]”类型。
2) 在第二次调用中,它给出 Gives TargetParameterCountException: {"Parameter count mismatch."}
为什么会这样?
using System;
using System.Threading;
using System.Windows.Forms;
namespace BeginInvokeArgsTest
{
public partial class Form1 : Form
{
private delegate void VoidDelegate(params object[] args);
private Delegate methodDelegate;
public Form1()
{
InitializeComponent();
methodDelegate = new VoidDelegate(SetLabelDelegate);
Thread t = new Thread(ChangeDay);
t.Start();
}
private void ChangeDay()
{
//Gives ArgumentException. 'System.String' cannot be converted to type 'System.Object[]'.
ChangeDay(new VoidDelegate(SetLabelDelegate), "Sunday" );
//Gives TargetParameterCountException: {"Parameter count mismatch."}
ChangeDay(new VoidDelegate(SetLabelDelegate), "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
}
private void ChangeDay(Delegate del, params object[] args)
{
if (this.InvokeRequired)
{
methodDelegate = del;
this.BeginInvoke(new VoidDelegate(RouterDelegate), args );
}
}
private void RouterDelegate(params object[] args)
{
methodDelegate.DynamicInvoke(args);
}
private void SetLabelDelegate(params object[] args)
{
foreach (object day in args)
{
label1.Text = day as string;
Thread.Sleep(1000);
}
}
}
}
PS:现在更正了错误的问题。对于老错误的问题,我真诚地道歉。我通常不会这么粗心。如果有的话,也请忽略语言语法错误。