c# - 动态创建线程

标签 c# multithreading

我知道如何使用线程和后台 worker ,但只能以“静态”方式使用(因此对它们进行硬编码)。但是我想用这样的东西

public static void StartThread(string _Method)
{
    Thread t = new Thread(() => _Method;
    t.Start();
}

我知道这会失败,因为 _Method 是一个字符串。我读过使用 delegates 但我不确定这将如何工作以及在这种情况下是否需要它。

我想在需要时为特定功能启动一个线程(因此动态创建线程)。

最佳答案

你可以使用 C# Task如果您想在不同线程上拆分工作,这正是您所需要的。否则请继续使用 Vlad 的回答并使用接受委托(delegate)的方法。

任务

Task.Factory.StartNew(() => Console.WriteLine("Hello from taskA."));

线程

public static Thread Start(Action action) {
    Thread thread = new Thread(() => { action(); });
    thread.Start();
    return thread;
}

// Usage
Thread t = Start(() => { ... });
// You can cancel or join the thread here

// Or use a method
Start(new Action(MyMethodToStart));

关于c# - 动态创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10313185/

相关文章:

c# - 删除文件夹/文件和子文件夹

c# - 如何使用 polly 启用超时策略

c++ - 原子写入后跟同一个变量的原子读取的屏障有多有效?

c++ - 命名(通用)线程安全数据结构?

c# - Rx CatchAll 用于未观察到的消息

c# - 自定义组合 4 个词典

c# - 将 Azure Blob 容器中的 file.bacpac 导入到 Azure SQL 数据库

具有持久资源的 Java 线程

android - 从 AsyncTask 调用 UI 线程方法

java - Hibernate 源代码中的 volatile 屏障将为 "syncs state with other threads"。如何?