LoginSignup
7
7

More than 5 years have passed since last update.

Windowsフォームアプリケーションの非同期処理

Posted at

別スレッドからフォームを更新するにはInvokeを使うらしい。Invokeとかラムダ式とか馴染みがなかったけど、今回サンプルを動かして感じが掴めたのでメモしとく。

サンプルソース

using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace invoketest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Task t;
        private void Form1_Load(object sender, EventArgs e)
        {
            t = new Task(() =>
            {
                for (;;)
                {
                    Action a = () =>
                    {
                        label1.Text = DateTime.Now.Second.ToString();
                    };
                    Invoke(a);
                    System.Threading.Thread.Sleep(1000);
                }
            });
            t.Start();
        }
    }
}

参考文献

川俣晶著 C#ショートコードプログラミング http://goo.gl/EblJNn

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