サンプル集  >  C#  >  スレッド
スレッド
2015/12/28

スレッドを使ってみます。

◆環境
OS Windows 7 Professional Service Pack 1 64bit
C# Microsoft Visual C# 2010 01018-587-4111284-70817

[ファイル]-[新規作成]-[プロジェクト]を選択。

[コンソール アプリケーション]を選択し、名前に「ThreadTest」と入力し「OK」。

Program.cs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
using System;
using System.Threading;

namespace ThreadTest
{
    class Program
    {
        // スレッドとして動作させる処理
        public static void MyThread( object param )
        {
            for ( int i = 0; i < ( int )param; i++ )
            {
                Console.WriteLine( "i={0}", i );
                Thread.Sleep( 500 );
            }
        }

        static void Main( string[] args )
        {
            // スレッドへ渡す引数を標準入力から取得
            Console.Write( "input count:" );
            string inpt = Console.ReadLine();

            // スレッドの生成
            Thread th
            = new Thread(
                new ParameterizedThreadStart( MyThread )
            );

            // スレッドの開始
            th.Start( int.Parse( inpt ) );

            // スレッドの終了待ち
            th.Join();

            Console.Write( "done." );
            Console.ReadKey();
        }
    }
}

実行します。

> TaskTest.exe
input count:5
i=0
i=1
i=2
i=3
i=4
done.

▲ PageTop  ■ Home


Copyright (C) 2015 ymlib.com