2 回答
TA贡献1848条经验 获得超2个赞
这是您需要做的:
private string search1_Text = "";
private string comboBox1_Text = "";
private void Instantiatesearch1Thread()
{
search1_Text = search1.Text;
comboBox1_Text = comboBox1.Text;
search1Thread.WorkerReportsProgress = true;
search1Thread.WorkerSupportsCancellation = true;
search1Thread.ProgressChanged += search1Thread_ProgressChanged;
search1Thread.DoWork += search1Thread_Dowrk;
search1Thread.RunWorkerCompleted += search1Thread_RunWorkerCompleted;
}
在运行后台工作程序之前,您基本上获取了所需数据的副本。
然后您只需访问DoWork代码中的字段:
void search1Thread_Dowrk(object sender, DoWorkEventArgs e)
{
int percentprogress = 0;
percentprogress++;
Thread.Sleep(1000);
// Search1 button event handler
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
using (SqlDataAdapter cmd = new SqlDataAdapter(comboBox1SQL, conn))
{
if (comboBox1_Text.Contains("ID"))
{
long para = long.Parse(search1_Text);
cmd.SelectCommand.Parameters.Add(new SqlParameter
{
ParameterName = "@combo1Par",
Value = para,
SqlDbType = SqlDbType.BigInt
});
}
else if (comboBox1_Text.Contains("Other Thing") || comboBox1_Text.Contains("Other Stuff"))
{
string para = search1_Text;
cmd.SelectCommand.Parameters.Add(new SqlParameter
{
ParameterName = "@combo1Par",
Value = "%" + para + "%",
SqlDbType = SqlDbType.NVarChar,
});
}
// Clear datatable if it contains any information and then fill it
// tab1datatable is a DataGridView
if (tab1table != null)
tab1table.Clear();
cmd.Fill(tab1table);
//tab1datatable.DataSource = tab1table;
// A bunch of expensive calculations
}
}
}
TA贡献1820条经验 获得超9个赞
我不确定这是否是一个好的解决方案,但这可行。CheckForIllegalCrossThreadCalls初始化时设置为 false BackgroundWorker。
private void Instantiatesearch1Thread()
{
// Initialize other stuff
CheckForIllegalCrossThreadCalls = false;
}
并在任务完成后将其设置为 false。
private void search1Thread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Do your work,
CheckForIllegalCrossThreadCalls = true;
}
- 2 回答
- 0 关注
- 87 浏览
添加回答
举报