スレッド間のセキュリティ更新コントロール

4738 ワード

 SafeCall :

using System;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

    public static class Extensions

    {

        public static void SafeCall(this Control ctrl, Action callback)

        {

            if (ctrl.InvokeRequired)

                ctrl.Invoke(callback);

            else

                callback();

        }

    }

}

 。 :

using System;

using System.Threading;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            ThreadPool.QueueUserWorkItem(h =>

            {

                for (var i = 0; i < 10000000; i++)

                {

                    label1.SafeCall(() =>

                    {

                        label1.Text = i.ToString();

                    });

                    Thread.Sleep(100);

                }

            });

        }

 

    }

}
 , lamda “ ”。 :



using System;

using System.Threading;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            ThreadPool.QueueUserWorkItem(h =>

            {

                for (var i = 0; i < 10000000; i++)

                {

                    label1.SafeCall(delegate()

                    {

                        label1.Text = i.ToString();

                    });

                    Thread.Sleep(100);

                }

            });

        }

 

    }

}