重新实例化线程

发布于 2024-10-31 10:45:58 字数 388 浏览 1 评论 0原文

我有以下代码,有人可以在下面澄清我的疑问吗?

public static void Main() {
    Thread thread = new Thread(Display);
    thread.Start();
    Thread.Sleep(5000);     
    // Throws exception, thread is terminated, cannot be restarted. 
    thread.Start() 
}

public static void Display() {

}

似乎为了重新启动线程,我必须再次重新实例化线程。这是否意味着我正在创建一个新线程?如果我继续创建 100 次重新启动,是否会创建 100 个线程并导致性能问题?

I have the following code, could anyone please clarify my doubt below.

public static void Main() {
    Thread thread = new Thread(Display);
    thread.Start();
    Thread.Sleep(5000);     
    // Throws exception, thread is terminated, cannot be restarted. 
    thread.Start() 
}

public static void Display() {

}

It seems like in order to restart the thread I have to re-instantiate the thread again. Does this means I am creating a new thread? If I keep on creating 100 re-instiation will it create 100 threads and cause performance issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

灰色世界里的红玫瑰 2024-11-07 10:45:58

是的,您要么必须创建一个新线程,要么每次都将任务交给线程池,以避免创建真正的新线程。您无法重新启动线程。

但是,我建议,如果您的任务连续执行 100 次失败,那么您遇到的问题比启动新任务的性能开销更大。

Yes, you either have to create a new thread or give the task to the thread pool each time to avoid a genuinely new thread being created. You can't restart a thread.

However, I'd suggest that if your task has failed to execute 100 times in a row, you have bigger problems than the performance overhead of starting new tasks.

心在旅行 2024-11-07 10:45:58

sleep后不需要启动线程,线程会自动唤醒。这是同一个线程。

You do not need to start the thread after sleep, the thread wake up automatically. It's the same thread.

初相遇 2024-11-07 10:45:58

首先,如果线程已经启动,则无法启动该线程。在您的示例中,线程已完成工作,这就是它处于终止状态的原因。

您可以使用以下方式检查状态:
线程.线程状态

first of all, you can't start the thread if it has already started. In your example, thread has finished it is work, that's why it is in terminated state.

you can check status using:
Thread.ThreadState

李白 2024-11-07 10:45:58

您是否尝试在 5 秒完成之前唤醒线程?在这种情况下,您可以尝试使用监视器(等待、脉冲等)

Are you trying to wake the thread up before the 5 seconds in complete? In which case you could try using Monitor (Wait, Pulse etc)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文