LoginSignup
19

More than 5 years have passed since last update.

posted at

updated at

別スレッドからのUI操作についての備忘録

簡単なメモ書き。

通常、非同期メソッド内からUI操作をしようとすると
Exceptionが発生します。
以下が回避の方法になります。

別スレッドからのUI操作

private async Task HeavyProcessingAsync()
{
    if (this.InvokeRequied)
    {
        //別スレッドによるUI操作
        this.Invoke((MethodInvoker)(() => TextBox.Text = "hoge"));
    }
    else
    {
        //UIスレッドからのUI操作
        TextBox.Text = "hoge";
    }
}

まずInvokeする必要があるかを判定して、
必要ならばInvokeメソッドとMethodInvokerデリゲートを利用します。


参考:スレッド セーフなコントロールの呼び出し

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
What you can do with signing up
19