如何在 C# 中从 Systems.Timers 线程调用 UI 方法
How do I invoke a UI method from a Systems.Timers thread in C#
我有一份 windows 表格申请。
我应该创建一个 SQL 作业,然后执行它。 SQL 作业包含大约 9 个步骤,大约需要 4 个小时才能完成。
我应该在数据网格视图中显示 SQL 作业的状态,这样就没有必要转到 SQL 服务器并监视事件。
我的代码如下
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread t1 = new Thread(FirstThread);
t1.Start();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 500;
timer.Enabled = true;
timer.Elapsed += timer1_Tick;
timer.Start();
t1.Join();
}
private void FirstThread()
{
// Creates a job
// Invoke the job, via a bat file
}
private void checkStatus()
{
// Checks the status of the job using the EXEC sp_helpjob @jobName='JobName'
// Populate the status on the DataGridView
// If the status of the job, eg.
dataGridView1.DataSource = ds.Tables[0];
int CurrentExecution = Convert.ToInt32(dt.Rows[0]["Current_Execution_Status"]);
if (CurrentExecution == 4)
label1.Text = "Job is Over";
}
private void timer1_Tick(object sender, EventArgs e)
{
checkStatus();
}
我运行进入CrossThread Operation Not valid错误。谁能告诉我如何在 System.Timer 线程中调用 UI 控件。
您应该在 Control
或 Form
上调用 Invoke
:
this.Invoke((MethodInvoker)delegate() { label1.Text = "Job is Over"; });
或者 BeginInvoke
如果您不想等到操作结束:
this.BeginInvoke((MethodInvoker)delegate() { label1.Text = "Job is Over"; });
我有一份 windows 表格申请。 我应该创建一个 SQL 作业,然后执行它。 SQL 作业包含大约 9 个步骤,大约需要 4 个小时才能完成。 我应该在数据网格视图中显示 SQL 作业的状态,这样就没有必要转到 SQL 服务器并监视事件。
我的代码如下
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread t1 = new Thread(FirstThread);
t1.Start();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 500;
timer.Enabled = true;
timer.Elapsed += timer1_Tick;
timer.Start();
t1.Join();
}
private void FirstThread()
{
// Creates a job
// Invoke the job, via a bat file
}
private void checkStatus()
{
// Checks the status of the job using the EXEC sp_helpjob @jobName='JobName'
// Populate the status on the DataGridView
// If the status of the job, eg.
dataGridView1.DataSource = ds.Tables[0];
int CurrentExecution = Convert.ToInt32(dt.Rows[0]["Current_Execution_Status"]);
if (CurrentExecution == 4)
label1.Text = "Job is Over";
}
private void timer1_Tick(object sender, EventArgs e)
{
checkStatus();
}
我运行进入CrossThread Operation Not valid错误。谁能告诉我如何在 System.Timer 线程中调用 UI 控件。
您应该在 Control
或 Form
上调用 Invoke
:
this.Invoke((MethodInvoker)delegate() { label1.Text = "Job is Over"; });
或者 BeginInvoke
如果您不想等到操作结束:
this.BeginInvoke((MethodInvoker)delegate() { label1.Text = "Job is Over"; });