LoginSignup
16
13

More than 5 years have passed since last update.

C#のWindowsフォームアプリケーションでメインスレッドのGUIを更新する方法

Last updated at Posted at 2017-09-19

いまさらな内容ですが、色々やり方があるようで、自分の場合はコレです。
※コメントでいただいたやり方に変えました!

// 呼び出すメソッドの定義(匿名メソッドを使う場合は不要)
public void writeToConsole(string msg)
{
    textbox.Text += msg + Environment.NewLine;
}
// マルチスレッドから呼び出す
if (InvokeRequired)
{
    // 戻り値がvoidで、引数がstring1個の場合
    Invoke( new Action<string>(writeToConsole), "解析終了" );
}
else
{
    textbox.Text += msg + Environment.NewLine;
}

もちろんThread.Start()だろうが、Task.Run()だろうが、この方法でOKです。

おまけ。匿名メソッドを使う場合はこちら。

Invoke( new Action(delegate (string msg) {textbox.Text += msg + Environment.NewLine;}), "解析終了" );

↑のラムダ式版。

Invoke( new Action<string>((msg) => textbox.Text += msg + Environment.NewLine) ), "解析終了" );

メソッドの引数がない場合や、戻り値がvoidでない場合

寂しいのでいくつか例を。
戻り値がvoidならAction、void以外ならFuncの定義済みデリゲートを使います。

戻り値がvoidで、引数なしの場合

// 呼び出すメソッドの定義
public void funcp0()
{
    ...
}
// マルチスレッドから呼び出す
Invoke( new Action(funcp0) );

戻り値がvoidで、引数がstringとintの2つの場合

// 呼び出すメソッドの定義
public void funcp2(string msg, int nLineNo)
{
    ...
}
// マルチスレッドから呼び出す
Invoke( new Action<string, int>(funcp2), "解析終了", 100 );

戻り値がdoubleで、引数がstringとintの2つの場合

// 呼び出すメソッドの定義
public double funcdp2(string d, int n)
{
    ...

    return 100.0;
}
// マルチスレッドから呼び出す
Invoke( new Action<string, int, double>(funcdp2), "50.0", 75 );

おまけ。匿名メソッドを使う場合はこちら。

Invoke( new Func<string, int, double>( delegate (string d, int n){ return double.Parse(d) + n + 100.0; } ), "50.0", 75 );

↑のラムダ式版。

Invoke( new Func<string, int, double>((d, n) => double.Parse(d) + n + 100.0) ), "50.0", 75 );
16
13
5

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
16
13