it编程 > 编程语言 > Asp.net

C#中ThreadStart委托的实现

19人参与 2025-05-20 Asp.net

1.threadstart 委托:

threadstart 是 .net 中的一个内置委托类型,表示无参数且无返回值的方法。其定义如下:

public delegate void 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 task = () => console.writeline("running in thread");
thread thread = new thread(task);
thread.start();

线程安全注意事项

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();

优点

6. 关键区别:threadstart vs action

特性threadstartaction
返回值无 (void)无 (void)
参数可带参数(如 action<int>
用途专用于 thread 构造函数通用委托
现代性较旧 api推荐使用

总结

根据实际需求选择合适方案,平衡控制精细度和开发效率。

到此这篇关于c#中threadstart委托的实现的文章就介绍到这了,更多相关c# threadstart委托内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

Linux使用perf跟踪.NET程序的mmap泄露的流程步骤

05-20

C#实现访问远程硬盘的图文教程

05-19

Core i5-12400F搭配RTX 5070 Ti合理吗? 七款游戏性能测评

05-19

C#使用ClosedXML进行读写excel操作

05-21

C#继承之里氏替换原则分析

05-21

C#使用MQTTnet实现服务端与客户端的通讯的示例

05-22

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论