3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

.NET CoreでThread.Sleepしたり、時間測ったり、ログ書き込んだり。

Last updated at Posted at 2016-11-24

.NET Coreでテストプログラム作成時に使う幾つかのクラスやメソッドが使えるか試してみました。

  • ストップウォッチ(時間計測)
  • Thread.Sleep(プログラムのスリープ)
  • 書込み(ログ等の書込み)

結論から言えば動きました。但し、Thread.Sleepは.NET Core用のライブリを読み込む必要があるようです。

準備

コンソールアプリの雛形を作ります。

mkdir test
cd test
dotnet new

package.json

package.jsonにSystem.Threadingを追加。dotnet restoreを実行。

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.1": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.1.0"
        },
+       "System.Threading.Thread": "*"
      },
      "imports": "dnxcore50"
    }
  }
}

Program.cs

各機能を使ってみる。ログはNlogやlog4netとかも利用できますが、「とりあえず」というときには普通の書込みで対応したいものです。.NET FrameworkのStreamWriterは直接ファイルを指定できましたが、.NET CoreではいったんFileStreamをかましてやる必要があるようです。

なお、.NET Coreから新しいLoggingフレームワークが加わっています。参考まで。

using System;
using System.Threading;
using System.Diagnostics;
using System.IO;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //stop watch
            Stopwatch sw = new Stopwatch();
            sw.Start();

            Console.WriteLine("Start.");

            //Sleep
            Thread.Sleep(2000);

            Console.WriteLine("End");

            sw.Stop();
            Console.WriteLine("Time is "+sw.Elapsed);

            //write log
            using(FileStream fs = new FileStream("./test.txt",FileMode.Append))
            using(StreamWriter writer = new StreamWriter(fs))
            {
                writer.WriteLine(DateTime.Now+"Time is "+sw.Elapsed);
            }
        }
    }
}
3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?