跨執行緒存取UI 跨執行緒存取UI
  .NET       ez      2012-06-04

WinFrom在執行緒下存取From上的物件會出現以下錯誤:

此時有三種方式可以解決,建議使用委派方式:

 

直接允許Cross Thread:

在WinFrom Load中加入:Form.CheckForIllegalCrossThreadCalls = false;

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

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

        //執行緒變數
        private Thread thread;

        private void Form1_Load(object sender, EventArgs e)
        {
            Form.CheckForIllegalCrossThreadCalls = false;
            thread = new Thread(() =>
            {
                int x = 0;
                while (++x > 0) ShowText(x);
            });
            thread.Start();
        }

        //顯示文字到label
        private void ShowText(int i)
        {
            label1.Text = i.ToString();
        }

        //表單關閉中
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thread.ThreadState != ThreadState.Stopped) thread.Abort();
        }
    }
}

透過Timer定時更新物件:

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

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

        //執行緒變數
        private Thread thread;
        private int x = 0;

        private void Form1_Load(object sender, EventArgs e)
        {
            thread = new Thread(() =>
            {
                while (++x > 0) ;
            });
            thread.Start();

            System.Windows.Forms.Timer T = new System.Windows.Forms.Timer();
            T.Tick += new EventHandler(T_Tick);
            T.Interval = 1;
            T.Start();
        }

        private void T_Tick(object sender, EventArgs e)
        {
            ShowText(x);
        }

        //顯示文字到label
        private void ShowText(int i)
        {
            label1.Text = i.ToString();
        }
    }
}

採用委派方式 (建議):

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

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

        //執行緒變數
        private Thread thread;
        //定義委派
        private delegate void deg(int i);

        private void Form1_Load(object sender, EventArgs e)
        {
            thread = new Thread(() =>
            {
                //建立委派物件
                deg d = new deg(ShowText);
                int x = 0;
                while (++x > 0) this.Invoke(d, x);
            });
            thread.Start();
        }

        //顯示文字到label
        private void ShowText(int i)
        {
            label1.Text = i.ToString();
        }

        //表單關閉中
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thread.ThreadState != ThreadState.Stopped) thread.Abort();
        }
    }
}

標籤:   .NET

我要留言