4
5

More than 1 year has passed since last update.

[Windows/WPF] バックグラウンドプロセスを作ってみる(.NET5版 別解)

Last updated at Posted at 2021-12-13

もくじ

やりたいこと

以前、.NET5でバックグラウンドプロセスを作ったが、もっと簡単かもしれない方法があったのでメモ。

手順

  1. 「WPFアプリケーション」を選択する。
    image.png

  2. ターゲットフレームワークで「.NET5.0」を選択する。
    image.png

  3. App.xamlの先頭のにあるStartupUri="MainWindow.xaml"を削除
    image.png

  4. App.xaml.cs にある「App」クラスに、OnStartup()メソッドのオーバーライドを追加する。
    (Appにカーソルを合わせて、ALT+Entを押し、出たメニューで「上書きの追加」を選択し、OnStartup()を選択する)

  5. 起動後5秒でアプリを終了するには、下記のように書く。

App.xaml.cs
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp10
{
    public partial class App : Application
    {
        protected override async void OnStartup(StartupEventArgs e)
        {
            await Task.Delay(5000);
            this.Shutdown();
        }
    }
}

App.xamlStartupUri="MainWindow.xaml"を消してないと、上のコードでTask.Delayしている間にウインドウが出てしまうので、必ず削除しておくこと。

前回のやり方との差

前回のやり方は下記。

前回のやり方と今回のやり方で、特に動きに違いはないように見える。

どちらも、

  • タスクマネージャーの
    • 「プロセス」タブには出てこない
    • 「詳細」タブには出てくる

同じ動きするのであれば、今回のやり方の方が、簡単かもしれない。

4
5
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
4
5