C# 消息:需要对象引用(Control.Invoke)
C# message: An object reference is required (with Control.Invoke)
我的代码在编译前显示如下错误信息
"An object reference is required"
错误代码是:
Control.Invoke(new invokeDelegate(invokeMethod));
我在 invokeMethod
实例之前放了一个 static
但它不起作用...
有谁知道如何解决这个问题?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Thread invokeThread;
private delegate void invokeDelegate();
private void StartMethod()
{
//Code C
Control.Invoke(new invokeDelegate(invokeMethod));
//Code D
}
private void invokeMethod()
{
//Code E
}
private void button1_Click(object sender, EventArgs e)
{
//Code A
invokeThread = new Thread(new ThreadStart(StartMethod));
invokeThread.Start();
//Code B
}
}
}
问题是您在 Control
class 本身上调用 Invoke。您需要在控件实例上调用 Invoke。
查看 https://msdn.microsoft.com/en-us/library/a1hetckb(v=vs.110).aspx 底部的示例代码,其中代码调用 myFormControl1.Invoke
.
我的代码在编译前显示如下错误信息
"An object reference is required"
错误代码是:
Control.Invoke(new invokeDelegate(invokeMethod));
我在 invokeMethod
实例之前放了一个 static
但它不起作用...
有谁知道如何解决这个问题?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Thread invokeThread;
private delegate void invokeDelegate();
private void StartMethod()
{
//Code C
Control.Invoke(new invokeDelegate(invokeMethod));
//Code D
}
private void invokeMethod()
{
//Code E
}
private void button1_Click(object sender, EventArgs e)
{
//Code A
invokeThread = new Thread(new ThreadStart(StartMethod));
invokeThread.Start();
//Code B
}
}
}
问题是您在 Control
class 本身上调用 Invoke。您需要在控件实例上调用 Invoke。
查看 https://msdn.microsoft.com/en-us/library/a1hetckb(v=vs.110).aspx 底部的示例代码,其中代码调用 myFormControl1.Invoke
.