您现在的位置是:首页 > 文章详情

C# 多线程、控制线程数提高循环输出效率

日期:2018-05-28点击:370
原文: C# 多线程、控制线程数提高循环输出效率

 

C#多线程及控制线程数量,对for循环输出效率。

 

虽然输出不规律,但是效率明显提高。

思路:

如果要删除1000条数据,只使用for循环,则一个接着一个输出。所以,把1000条数据分成seed段,每段10条数据。

int seed = Convert.ToInt32(createCount.Value) % 10 == 0 ? Convert.ToInt32(createCount.Value) / 10 : Convert.ToInt32(createCount.Value) / 10 + 1;

注:createCount.Value的值是具体输出数据的数量

这里把数据分配给seed个线程去处理,每个线程只输出10个数据。

 int threadCountTmp = 0;//任务线程分派数 private void btnCreate_Click(object sender, EventArgs e) { int seed = Convert.ToInt32(createCount.Value) % 10 == 0 ? Convert.ToInt32(createCount.Value) / 10 : Convert.ToInt32(createCount.Value) / 10 + 1; for (int i = 0; i < seed; i++) { Thread threadTmp = new Thread(new ParameterizedThreadStart(TempOut)); threadTmp.Start(i); threadCountTmp++; Application.DoEvents();//响应窗口状态 while (true) { if (threadCountTmp < 10) break; }//推拉窗式控制多线程 线程数10  } } //分段后的数据发布给其它线程 public void TempOut(object o) { int tmp=Convert.ToInt32(o)*10; int i = tmp; for (; i < (tmp+10<=createCount.Value?tmp+10:createCount.Value); i++) { Thread thread = new Thread(new ParameterizedThreadStart(ResultOut)); thread.Start(i); threadCount++; while (true) { if (threadCount < 10) break; }//推拉窗式控制多线程 线程数10  } threadCountTmp--; }

分段后,再将分段后的数据分配给其它线程来处理,这样就能多线程同时工作了,由于要对控件操作,所以使用多线程的话要依靠委托来实现多线程对控件的控制。所以最后一步的输出,如下:

 delegate void TextTmp(object o);//声明委托 int threadCount = 0;//任务线程 //委托函数 public void ResultOut(object o) { if (!txtResult.InvokeRequired) { txtResult.Text = "\n" + f_groundcode.Text + "," + f_ticketno.Text + DateTime.Now.ToLongDateString().Replace("-", "") + GetZero(6 - o.ToString().Length) + o.ToString() + "," + DateTime.Now.ToLongDateString().Replace("-", "") + DateTime.Now.ToLongTimeString().Replace(":", "") + txtResult.Text; } else { TextTmp tmpDel = new TextTmp(ResultOut); this.Invoke(tmpDel,o); } threadCount--; }

因为我的数据要保证位数,所以要对0做简单处理。例如 我要输出

000000

000001

000002

000003

........

从上面的代码可以看出,我是使用for来递增的。所以是整型,前面的0随着数值的大小不断改变个数。

 //处理数字前面有多少个0 private string GetZero(int leng) { string result = ""; for (int i = 0; i < leng; i++) { result += "0"; } return result; }

好了。简单的多线程处理。希望大家可以学习。欢迎大家指导~~

 

 

原文链接:https://yq.aliyun.com/articles/678460
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章