C# InvokeとBeginInvoke

Standard

Form1.cs

using System;
using System.Windows.Forms;
using System.Threading;
 
namespace ThreadTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public delegate void invokeDelegate();
        public void ConsolePrint(String tmp)
        {
            Console.WriteLine(DateTime.Now.ToString("mmssffff") + " - " + "Thread" + Thread.CurrentThread.GetHashCode().ToString() + tmp);
        }
        private void Button1_Click(object sender, EventArgs e)
        {
            ConsolePrint(" Button1_Click!");
            Thread.Sleep(1000);
            ConsolePrint("... Sleep 1s ...");
 
            Thread invokeThread = new Thread(new ThreadStart(StartMethod));
            invokeThread.Start();
            Thread.Sleep(5000);
            ConsolePrint("... Sleep 5s ...");
            string a = string.Empty;
            for (int i = 0; i < 5; i++)
            {
                a = a + " Loop";
            }
            ConsolePrint(": " + a);
        }
        private void StartMethod()
        {
            ConsolePrint(" StartMethod 1");
 
            button1.Invoke(new invokeDelegate(invokeMethod));
            //button1.BeginInvoke(new invokeDelegate(invokeMethod));
 
            Thread.Sleep(1000);
            ConsolePrint("... Sleep 1s ...");
            ConsolePrint(" StartMethod 2");
        }
        private void invokeMethod()
        {
            ConsolePrint(" invokeMethod");
        }
    }
}

Output:

Invoke
21443499 - Thread1 Button1_Click!
21453526 - Thread1... Sleep 1s ...
21453586 - Thread3 StartMethod 1
21503540 - Thread1... Sleep 5s ...
21503540 - Thread1:  Loop Loop Loop Loop Loop
21503550 - Thread1 invokeMethod
21513556 - Thread3... Sleep 1s ...
21513556 - Thread3 StartMethod 2
The thread 0x1fac has exited with code 0 (0x0).
 
BeginInvoke
22253337 - Thread1 Button1_Click!
22263366 - Thread1... Sleep 1s ...
22263406 - Thread3 StartMethod 1
22273422 - Thread3... Sleep 1s ...
22273422 - Thread3 StartMethod 2
The thread 0x3b38 has exited with code 0 (0x0).
22313375 - Thread1... Sleep 5s ...
22313375 - Thread1:  Loop Loop Loop Loop Loop
22313385 - Thread1 invokeMethod

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.