您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

C#多线程编程实例-线程与窗体交互的代码分析

2024/3/16 17:39:15发布24次查看
c#多线程编程实例 线程与窗体交互
代码:
public partial class form1 : form { //声明线程数组 thread[] workthreads = new thread[10]; public form1() { initializecomponent(); } //此委托允许异步的调用为listbox添加item delegate void additemcallback(string text); //这种方法演示如何在线程安全的模式下调用windows窗体上的控件。 private void additem(string text) { if (this.listbox1.invokerequired) { additemcallback d = new additemcallback(additem); this.invoke(d, new object[] { text }); } else { this.listbox1.items.add(text); } } //数据采集方法 public void dataget() { while (true) { additem("ok"); thread.sleep(1000); } //如果此方法退出了,那么这个线程也就退出了 } /// <summary> /// 启动线程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_click(object sender, eventargs e) { //循环创建并启动线程执行 for (int i = 0; i < workthreads.length; i++) { if (workthreads[i] == null) { //如果线程不存在,则创建 workthreads[i] = new thread(new threadstart(dataget)); workthreads[i].name = i.tostring(); workthreads[i].start(); } else { //已经存在,如果没有运行,则启动 if (workthreads[i].threadstate == threadstate.aborted || workthreads[i].threadstate == threadstate.stopped) { workthreads[i] = new thread(new threadstart(dataget)); workthreads[i].name = i.tostring(); workthreads[i].start(); }else{ workthreads[i].start(); } } } } /// <summary> /// 停止线程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_click(object sender, eventargs e) { //循环停止线程执行 for (int i = 0; i < workthreads.length; i++) { //如果线程存在,并且状态不是停止也不是终止的,则终止该线程 if (workthreads[i] != null && workthreads[i].threadstate != threadstate.stopped && workthreads[i].threadstate != threadstate.aborted) { workthreads[i].abort(); } } }
以上就是c#多线程编程实例-线程与窗体交互的代码分析的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product