【C#】避免UI無響應的空間invoke和begininvoke方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private delegate void test(string str);

        private void button1_Click(object sender, EventArgs e)
        {

           Task.Factory.StartNew(()=> {
               string flag = "";
               int i;
               Thread.Sleep(5000);
               flag = "asdf";
               textBox1.Invoke(new test(testhandler1), flag);
               for( i = 0; i < 6; i++)
               {
                   Thread.Sleep(1000);
               }
           textBox2.BeginInvoke(new test(testhandler2), i.ToString() );
           });

        }

        private void testhandler1(string str)
        {

            Thread.Sleep(5000);

            textBox1.Text = str;
           // textBox2.Text = str;

        }

        private void testhandler2(string str)
        {

           // Thread.Sleep(5000);

            textBox2.Text = str;

        }
    }
}

控件的BeginInvoke方法可以保證在調用BeginInvoke的方法的線程異步方式運行委託的代碼(testhandler)。

而Invoke方法是同步執行委託的方法(testhandler)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章