1.threadstart 委托:
threadstart
是 .net 中的一个内置委托类型,表示无参数且无返回值的方法。其定义如下:
public delegate void threadstart();
通常用于定义线程的入口方法。
list<threadstart>
:
这是一个泛型集合,用于存储多个threadstart
委托实例。每个委托代表一个待执行的任务。整体作用:
创建一个线程任务队列,用于保存需要通过线程执行的多个方法。
2. 典型使用场景
private list<threadstart> delegates = new list<threadstart>();
(1) 多任务队列管理
// 添加任务到队列 delegates.add(() => console.writeline("task 1")); delegates.add(() => file.writealltext("test.txt", "hello")); // 启动线程执行所有任务 foreach (var task in delegates) { new thread(task).start(); }
(2) 延迟执行控制
// 先收集任务 delegates.add(() => downloadfile(url1)); delegates.add(() => processdata(data)); // 在适当时候触发执行 void executealltasks() { foreach (var task in delegates) { new thread(task).start(); } }
3. 技术细节
委托与线程的关系
每个
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); } }
4. 完整使用示例
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();
5. 替代方案(现代c#推荐)
使用 task 和 concurrentqueue
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
6. 关键区别:threadstart vs action
特性 | threadstart | action |
---|---|---|
返回值 | 无 (void ) | 无 (void ) |
参数 | 无 | 可带参数(如 action<int> ) |
用途 | 专用于 thread 构造函数 | 通用委托 |
现代性 | 较旧 api | 推荐使用 |
总结
原始代码:创建了一个传统的线程任务队列,适用于需要显式管理
thread
的场景。现代替代:推荐使用
task
+concurrentqueue
组合,更符合当前 .net 的并发编程最佳实践。线程安全:若坚持使用
list<threadstart>
,必须通过锁机制保证线程安全。
根据实际需求选择合适方案,平衡控制精细度和开发效率。
到此这篇关于c#中threadstart委托的实现的文章就介绍到这了,更多相关c# threadstart委托内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论