C# 如何在单独的线程中启动长时间运行的进程
好了,最后一部分差不多完成了!有一个错误要转到hmmmmm。 我认为这是在使用建议,是在抱怨代表们C# 如何在单独的线程中启动长时间运行的进程,c#,sql,multithreading,C#,Sql,Multithreading,好了,最后一部分差不多完成了!有一个错误要转到hmmmmm。 我认为这是在使用建议,是在抱怨代表们 using System; public partial class Form1 : Form { public Form1() { InitializeComponent(); pictureBox2.Visible = false; } private void button1_Click(object se
using System;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox2.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
Task t = new Task(() => GetsalesFigures(accCollection.Text));
t.Start();
}
private void SetPictureBoxVisibility(bool IsVisible)
{
if (pictureBox2.InvokeRequired)
{
pictureBox2.Invoke(new Action<bool>(SetPictureBoxVisibility), new Object[] { IsVisible });
}
else
{
pictureBox2.Visible = IsVisible;
}
}
private void SetCheckBoxValue(bool IsChecked)
{
if (checkBox1.InvokeRequired)
{
pictureBox2.Invoke(new Action<bool>(SetCheckBoxValue), new Object[] { IsChecked });
}
else
{
checkBox1.Checked = IsChecked;
}
}
private void AddItem(string value)
{
if (accCollection.InvokeRequired)
{
accCollection.Invoke(new Action<string>(AddItem), new Object[] { value });
}
else
{
accCollection.Items.Add(value);
}
}
private void Form1_Load(object sender, EventArgs e)
{
AutofillAccounts();
}
private void GetsalesFigures(string Acct)
{
try
{
string myConn = "Server=af" +
"Database=sdfta;" +
"uid=busdf4;" +
"pwd=drsdft;" +
"Connect Tisdf=120;";
string acct;// test using 1560
SqlConnection conn = new SqlConnection(myConn);
SqlCommand Pareto = new SqlCommand();
BindingSource bindme = new BindingSource();
SqlDataAdapter adapt1 = new SqlDataAdapter(Pareto);
DataSet dataSet1 = new DataSet();
DataTable table1 = new DataTable();
//CREATE THE THREAD
//acct = accCollection.Text;
acct = Acct;
string fromDate = this.dateTimePicker1.Value.ToString("MM/dd/yyyy");
string tooDate = this.dateTimePicker2.Value.ToString("MM/dd/yyyy");
Pareto.Connection = conn;
Pareto.CommandType = CommandType.StoredProcedure;
Pareto.CommandText = "dbo.GetSalesParetotemp";
Pareto.CommandTimeout = 120;
Pareto.Parameters.AddWithValue("@acct", acct);
Pareto.Parameters.AddWithValue("@from", fromDate);
Pareto.Parameters.AddWithValue("@too", tooDate);
//pictureBox2.Visible = true;
//checkBox1.Checked = true;
SetCheckBoxValue(true);
SetPictureBoxVisibility(true);
adapt1.Fill(dataSet1, "Pareto");
//checkBox1.Checked = false;
//pictureBox2.Visible = false;
SetCheckBoxValue(false);
SetPictureBoxVisibility(true);
this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = dataSet1;
this.dataGridView1.DataMember = "Pareto";
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCells);
SetPictureBoxVisibility(true);
acct = Acct;
}
catch (Exception execc)
{
MessageBox.Show("Whoops! Seems we couldnt connect to the server!"
+ " information:\n\n" + execc.Message + execc.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
private void AutofillAccounts()
{
//get customers list and fill combo box on form load.
try
{
string myConn1 = "Server=sdf33;" +
"Database=sdft;" +
"uid=bdf4;" +
"pwd=ddft;" +
"Connect Timeout=6000;";
SqlConnection conn1 = new SqlConnection(myConn1);
conn1.Open();
SqlCommand accountFill = new SqlCommand("SELECT keycode FROM dbo.Customer", conn1);
SqlDataReader readacc = accountFill.ExecuteReader();
while (readacc.Read())
{
AddItem(readacc.GetString(0).ToString());
}
conn1.Close();
}
catch(Exception exc1)
{
MessageBox.Show("Whoops! Seems we couldnt connect to the server!"
+ " information:\n\n" + exc1.Message + exc1.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
}
使用系统;
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
pictureBox2.可见=假;
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
Task t=新任务(()=>GetsalesFigures(accCollection.Text));
t、 Start();
}
私有void setPictureBoxibility(布尔值可见)
{
如果(pictureBox2.InvokeRequired)
{
调用(新操作(setPictureBoxibility),新对象[]{IsVisible});
}
其他的
{
pictureBox2.Visible=可见;
}
}
私有void SetCheckBoxValue(布尔值已检查)
{
如果(复选框1.invokererequired)
{
调用(新操作(SetCheckBoxValue),新对象[]{IsChecked});
}
其他的
{
checkBox1.Checked=IsChecked;
}
}
专用void附加项(字符串值)
{
if(accCollection.invokererequired)
{
调用(新操作(AddItem),新对象[]{value});
}
其他的
{
accCollection.Items.Add(增值);
}
}
私有void Form1\u加载(对象发送方、事件参数e)
{
自动填充帐户();
}
私有void GetsalesFigures(字符串帐户)
{
尝试
{
字符串myConn=“Server=af”+
“数据库=sdfta;”+
“uid=busdf4;”+
“pwd=drsdft;”+
“连接Tisdf=120;”;
string acct;//使用1560进行测试
SqlConnection conn=新的SqlConnection(myConn);
SqlCommand Pareto=新SqlCommand();
BindingSource bindme=新的BindingSource();
SqlDataAdapter Adapte1=新的SqlDataAdapter(Pareto);
DataSet dataSet1=新数据集();
DataTable1=新的DataTable();
//创建线程
//acct=accCollection.Text;
acct=acct;
string fromDate=this.dateTimePicker1.Value.ToString(“MM/dd/yyyy”);
字符串tooDate=this.dateTimePicker2.Value.ToString(“MM/dd/yyyy”);
帕累托连接=连接;
Pareto.CommandType=CommandType.StoredProcess;
Pareto.CommandText=“dbo.GetSalesParetotemp”;
Pareto.CommandTimeout=120;
Pareto.Parameters.AddWithValue(“@acct”,acct);
Pareto.Parameters.AddWithValue(“@from”,fromDate);
Pareto.Parameters.AddWithValue(“@too”,tooDate);
//pictureBox2.Visible=true;
//checkBox1.Checked=true;
SetCheckBoxValue(真);
SetPictureBoxibility(真);
1.填充(数据集1,“帕累托”);
//checkBox1.Checked=false;
//pictureBox2.可见=假;
SetCheckBoxValue(假);
SetPictureBoxibility(真);
this.dataGridView1.AutoGenerateColumns=true;
this.dataGridView1.DataSource=dataSet1;
this.dataGridView1.DataMember=“Pareto”;
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCells);
SetPictureBoxibility(真);
acct=acct;
}
catch(异常execc)
{
Show(“哎呀!好像我们无法连接到服务器!”
+“信息:\n\n”+execc.Message+execc.StackTrace,
“致命错误”,MessageBoxButtons.OK,MessageBoxIcon.Stop);
}
}
私有无效自动填充帐户()
{
//获取客户列表并在表单加载时填写组合框。
尝试
{
string myConn1=“服务器=sdf33;”+
“数据库=sdft;”+
“uid=bdf4;”+
“pwd=ddft;”+
“连接超时=6000;”;
SqlConnection conn1=新的SqlConnection(myConn1);
conn1.Open();
SqlCommand accountFill=newsqlcommand(“从dbo.Customer中选择keycode”,conn1);
SqlDataReader readacc=accountFill.ExecuteReader();
while(readacc.Read())
{
AddItem(readacc.GetString(0.ToString());
}
conn1.Close();
}
捕获(异常exc1)
{
Show(“哎呀!好像我们无法连接到服务器!”
+“信息:\n\n”+exc1.Message+exc1.StackTrace,
“致命错误”,MessageBoxButtons.OK,MessageBoxIcon.Stop);
}
}
}
}
不确定应该在何处进行更改,现在是否应该在account方法中进行更改?您的代码中有很多问题:
- 调用
是一个阻塞调用。在您关闭表单之前,它不会返回。 因此,当应用程序即将退出时,线程将启动 只需在调用Run()之前启动线程: 提示:开始使用调试器并逐步完成代码。您可能已经注意到,您的线程函数从未达到Application.Run()
- 在函数
中创建Form1的第二个实例。在轮询复选框的状态时,必须使用现有实例GetSalesFigures
- 线程将只执行一次检查,然后返回。您必须在
中编写一些代码,等待用户选中复选框。否则什么也不会发生。 您可以使用GetSalesFigures
等待事件:ManualResetEvent
以您的形式:ManualResetEvent mre = new ManualResetEvent(false); void YourThreadFunc() { // Wait until someone signals mre mre.WaiteOne(); // start sql ... }
private void button1_Click(object sender, EventArgs e) { // trigger the WaitHandle to signal the waiting thread mre.Set(); }
- 调用
Appl
private void button1_Click(object sender, EventArgs e) { // trigger the WaitHandle to signal the waiting thread mre.Set(); }
public Form1() { InitializeComponent(); pictureBox2.Visible = false; } private void Form1_Load(object sender, EventArgs e) { AutofillAccounts(); } private void button1_Click(object sender, EventArgs e) { checkBox1.Checked = true; string acct = accCollection.Text; Task t = new Task(() => GetsalesFigures(acct)); t.Start(); } private void GetsalesFigures(String Acct) { // (...) //pictureBox2.Visible = true; use SetPictureBoxVisibility SetPictureBoxVisibility(true); //checkBox1.Checked = true; use SetCheckBoxValue SetCheckBoxValue(true); // (...) SetCheckBoxValue(false); SetPictureBoxVisibility(false); // (...) acct = Acct; // (...) SetDataGrid(true, dataSet1, "Pareto", DataGridViewAutoSizeColumnsMode.AllCells); } private void AutofillAccounts() { // (...) while (readacc.Read()) { AddItem(readacc.GetString(0).ToString()); } } private void SetCheckBoxValue(bool IsChecked) { if (checkBox1.InvokeRequired) { pictureBox2.Invoke(new Action<bool>(SetCheckBoxValue), new Object[] { IsChecked }); } else { checkBox1.Checked = IsChecked; } } private void SetPictureBoxVisibility(bool IsVisible) { if (pictureBox2.InvokeRequired) { pictureBox2.Invoke(new Action<bool>(SetPictureBoxVisibility), new Object[] { IsVisible }); } else { pictureBox2.Visible = IsVisible; } } // Your latest comment private void AddItem(string value) { if (accCollection.InvokeRequired) { accCollection.Invoke(new Action<string>(AddItem), new Object[] { value }); } else { accCollection.Items.Add(value); } } private void SetDataGrid(bool AutoGenerateColumns, Object DataSource, String DataMember, DataGridViewAutoSizeColumnsMode Mode) { if (this.dataGridView1.InvokeRequired) { this.dataGridView1.Invoke(new Action<bool, Object, String, DataGridViewAutoSizeColumnsMode>(SetDataGrid), AutoGenerateColumns, DataSource, DataMember, Mode); } else { this.dataGridView1.AutoGenerateColumns = AutoGenerateColumns; this.dataGridView1.DataSource = DataSource; this.dataGridView1.DataMember = DataMember; dataGridView1.AutoResizeColumns(Mode); } }
static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }