LoginSignup
9
12

More than 5 years have passed since last update.

C#で特定タイミングまでスレッドを待機させる

Last updated at Posted at 2016-09-11

はじめに

スレッド実行中、特定のタイミングまでスレッドを待機させる方法を紹介します。
なお、サンプルコードを動作させるには、C#4.0 に対応している必要があります。

方法

特定のタイミングまでスレッドを待機させるには、ManualResetEvent を使用します。
このクラスを使用し、WaitOne で待機中のスレッドに対して、Set() を呼び出すことで続行することが可能です。
以下にサンプルコードを示します。

サンプルコード

sample.cs
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    static class Program
    {
        static void Main(string[] args)
        {
            var waitHandle = new ManualResetEvent(false);
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(2000);
                waitHandle.Set();
            });


            Console.WriteLine("Wait");
            waitHandle.WaitOne(Timeout.Infinite);
            Console.WriteLine("Start");

            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
    }
}
9
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
12