C#多线程传递参数及任务用法示例
程序员文章站
2022-05-28 19:21:39
本文实例讲述了c#多线程传递参数及任务用法。分享给大家供大家参考,具体如下:
using system;
using system.collections.ge...
本文实例讲述了c#多线程传递参数及任务用法。分享给大家供大家参考,具体如下:
using system; using system.collections.generic; using system.linq; using system.text; using system.threading; namespace consolesample { class program { static void main(string[] args) { console.writeline("这是主线程"); datetime dtstart = datetime.now; for (int i = 0; i < 100; i++) { student s = new student(); s.name = "张三" + i; s.sex = "男"; s.age = 28; thread t = new thread(threadwithparas); t.start(s); //要给线程传递数据,需某个存储数据的类或结构 } datetime dtend = datetime.now; timespan span = (timespan)(dtend - dtstart); console.readline(); console.writeline("运行的时间 " + span.milliseconds); console.readline(); } static void threadwithparas(object o) { student s = o as student; console.writeline("这是分线程" + thread.currentthread.managedthreadid + " " + s.name + "---" + s.sex + "---" + s.age); } } public class student { public string name; public string sex; public int age; } }
using system; using system.collections.generic; using system.linq; using system.text; using system.threading; using system.threading.tasks; namespace consolesample { class program { static void main(string[] args) { //任务层次结构 task parent = new task(parenttask); parent.start(); thread.sleep(2000); console.writeline(parent.status); thread.sleep(4000); console.writeline(parent.status); console.readline(); } //父任务 static void parenttask() { console.writeline("task id {0}", task.currentid); task child = new task(childtask); // , taskcreationoptions.detachedfromparent); child.start(); thread.sleep(1000); console.writeline("parent started child"); // thread.sleep(3000); } //子任务 static void childtask() { console.writeline("child"); thread.sleep(5000); console.writeline("child finished"); } } }
更多关于c#相关内容感兴趣的读者可查看本站专题:《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结》
希望本文所述对大家c#程序设计有所帮助。