多进程操作--模拟二维码的扫描以及定期存储
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Thread t1,t2; private static DataTable tdlData = new DataTable("Datas"); private DataColumn dc = tdlData.Columns.Add("ProductId", Type.GetType("System.String")); private List<string> ProductName; private bool flag = false; private static string RowName; //获取数据源 public void GetData() { DataRow newRow = tdlData.NewRow(); if (!string.IsNullOrEmpty(RowName)) { newRow["ProductId"] = RowName; tdlData.Rows.Add(newRow);//将每条记录插入到临时表 } //模拟的时候可以设定每有5条数据的时候,传递一次参数 //但是实际应用的时候应该怎么办呢? if (tdlData.Rows.Count == 5) { flag = true; // tdlData.Reset(); } MessageBox.Show("临时表记录条数" + tdlData.Rows.Count); } public void ToList() { mut.WaitOne(); //Monitor.Enter(this); //lock (this) //{ if (flag) { ProductName = new List<string>();
for (int i = 0; i < tdlData.Rows.Count; i++) { ProductName.Add(tdlData.Rows[i].ItemArray[0].ToString()); } MessageBox.Show("存入数据库的数据条数" + ProductName.Count.ToString());
flag = false; tdlData.Rows.Clear(); }
//} //Monitor.Exit(this); mut.ReleaseMutex();
} private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (t1.IsAlive) { t1.Abort(); }
if (t2.IsAlive) { t2.Abort(); }
} private void Form1_Activated(object sender, EventArgs e) { this.txtInput.Focus(); } private void txtInput_KeyUp(object sender, KeyEventArgs e) { if (this.txtInput.Text.Length == 5) { this.txtInput.Focus(); this.listBox1.Items.Add(txtInput.Text.Trim()); RowName = txtInput.Text.Trim(); t1 = new Thread(new ThreadStart(this.GetData)); t1.Start(); t2 = new Thread(new ThreadStart(this.ToList)); t2.Start(); } else if (txtInput.Text.Length > 5) { this.txtInput.Clear(); } } }
注:这个程序模拟没有问题,但是实际操作的时候该怎么办呢?
实际操作的时候不可能定义一个数字,每当扫描一定数量的时候就把数据搞到DataTable中,
比如说,设定1000个,但是今天就生产了10001个,前10000个当然没有问题,插入数据库什么的都没事,
但是剩下的那一个该怎么处理?
所以说,定义一个具体数字是不切合实际的,征求想法!!!!
如果你有更好的想法,请留言或者联系本人,不甚感激!
QQ:834217941半部論語
- 4楼AllCanResolved5天前 11:15
- public void ToList()n {n //mut.WaitOne();n Monitor.Enter(this);n //lock (this)n //{n Thread.Sleep(10000);n if (flag== false)n {n ProductName = new List<string>();nn for (int i = 0; i < tdlData.Rows.Count; i++)n {n ProductName.Add(tdlData.Rows[i].ItemArray[0].ToString());n }n MessageBox.Show("存入数据库的数据条数" + ProductName.Count.ToString());nn //flag = false;n tdlData.Rows.Clear();n }nn //}n Monitor.Exit(this);n //mut.ReleaseMutex();n }nn这样模拟可以了,你一边填入信息,每隔10秒就处理数据一次,同时干掉临时的数据
- 3楼xomix5天前 11:15
- 实际操作建议一定时间入库一次,数量入库不靠谱的
- 2楼AllCanResolved5天前 11:00
- 如果大家还有更好的方法,除了多线程以外的方法什么的,请留言,公共进步,与诸君共勉励!
- 1楼AllCanResolved5天前 09:04
- 嗯 数据入库确实不靠谱 ,n程序修改如下:npublic void GetData()n{n DataRow newRow = tdlData.NewRow();n if (!string.IsNullOrEmpty(RowName))n {n newRow["ProductId"] = RowName;n tdlData.Rows.Add(newRow);//将每条记录插入到临时表 n }nn //模拟的时候可以设定每有5条数据的时候,传递一次参数n //但是实际应用的时候应该怎么办呢?n //if (tdlData.Rows.Count == 5)n //{n // flag = true;n //}n MessageBox.Show("临时表记录条数" + tdlData.Rows.Count);n}
