19人参与 • 2025-05-20 • Asp.net
threadstart
是 .net 中的一个内置委托类型,表示无参数且无返回值的方法。其定义如下:
public delegate void threadstart();
通常用于定义线程的入口方法。
list<threadstart>
:
这是一个泛型集合,用于存储多个 threadstart
委托实例。每个委托代表一个待执行的任务。
整体作用:
创建一个线程任务队列,用于保存需要通过线程执行的多个方法。
private list<threadstart> delegates = new list<threadstart>();
// 添加任务到队列 delegates.add(() => console.writeline("task 1")); delegates.add(() => file.writealltext("test.txt", "hello")); // 启动线程执行所有任务 foreach (var task in delegates) { new thread(task).start(); }
// 先收集任务 delegates.add(() => downloadfile(url1)); delegates.add(() => processdata(data)); // 在适当时候触发执行 void executealltasks() { foreach (var task in delegates) { new thread(task).start(); } }
每个 threadstart
委托可以传递给 thread
构造函数,作为线程启动时执行的方法。
示例:
threadstart task = () => console.writeline("running in thread"); thread thread = new thread(task); thread.start();
非线程安全集合:list<t>
本身不是线程安全的。若多线程同时修改集合(如添加/删除任务),需加锁:
private readonly object _lock = new object(); void addtask(threadstart task) { lock (_lock) { delegates.add(task); } }
using system; using system.collections.generic; using system.threading; class taskscheduler { private list<threadstart> _tasks = new list<threadstart>(); private readonly object _lock = new object(); public void addtask(action action) { lock (_lock) { _tasks.add(new threadstart(action)); } } public void executeall() { list<thread> threads = new list<thread>(); lock (_lock) { foreach (var task in _tasks) { thread thread = new thread(task); threads.add(thread); thread.start(); } _tasks.clear(); } // 等待所有线程完成(可选) foreach (var thread in threads) { thread.join(); } } } // 使用示例 var scheduler = new taskscheduler(); scheduler.addtask(() => console.writeline("task 1")); scheduler.addtask(() => thread.sleep(1000)); scheduler.executeall();
using system.collections.concurrent; using system.threading.tasks; private concurrentqueue<action> _taskqueue = new concurrentqueue<action>(); // 添加任务 _taskqueue.enqueue(() => console.writeline("task 1")); // 并行执行 parallel.foreach(_taskqueue, task => task.invoke()); _taskqueue.clear();
更高效的线程池管理(通过 task
)
天生线程安全的集合(concurrentqueue
)
支持 async/await
特性 | threadstart | action |
---|---|---|
返回值 | 无 (void ) | 无 (void ) |
参数 | 无 | 可带参数(如 action<int> ) |
用途 | 专用于 thread 构造函数 | 通用委托 |
现代性 | 较旧 api | 推荐使用 |
原始代码:创建了一个传统的线程任务队列,适用于需要显式管理 thread
的场景。
现代替代:推荐使用 task
+ concurrentqueue
组合,更符合当前 .net 的并发编程最佳实践。
线程安全:若坚持使用 list<threadstart>
,必须通过锁机制保证线程安全。
根据实际需求选择合适方案,平衡控制精细度和开发效率。
到此这篇关于c#中threadstart委托的实现的文章就介绍到这了,更多相关c# threadstart委托内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论