等待一个线程真正开始用C# [英] Wait for a thread to actually start in c#

查看:112
本文介绍了等待一个线程真正开始用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要启动一个线程,而是继续刚才的线程实际运行。现在我的code是这样的:

I need to start a thread, but continue just after the thread is actually running. Now my code looks like:

        splashthread.IsBackground = false;
        splashthread.Start();
        Thread.Sleep(100); // Wait for the thread to start

我不喜欢这些巫毒睡大觉(至少可以这样说),所以我在寻找做上述的更漂亮的方式。

I'm not fond of these voodoo sleeps (to say the least), so I'm looking for more nifty way of doing the above.

任何想法?

推荐答案

事情是这样的:

var splashStart = new ManualResetEvent(false);

var splashthread = new Thread(
  () =>
  {
     splashStart.Set();
     // Your thread code here...
  });

splashthread.Start();
splashStart.WaitOne();

不要忘了Dipose splashStart ,或者如果它适合你的code使用使用

Don't forget to Dipose splashStart or if it's appropriate in your code use a using block.

编辑:没有确认原来的code在IDE中。改变等到了WaitOne()按下面的评论。

Didn't confirm the original code in the IDE. Changed Wait to WaitOne() as per comment below.

这篇关于等待一个线程真正开始用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆