본문 바로가기
C#(CSharp)/WPF

UI 쓰레드 (UI Thread)

by swconsulting 2015. 3. 21.

UI Thread에서 Invoke, BeginInvoke 차이를 알고 있어야 한다.


Invoke : Syncronize

BeginInvoke : Asynchronize 



1. Simple Way


Application.Current.Dispatcher.BeginInvoke(new Action(() => { SaveAllNoteToXml(); /* Your code here */ }));


2.Ordinary Way

using System;

using System.Windows;

using System.Threading.Tasks;


namespace WpfApp

{

    /// <summary>

    /// Interaction logic for MainWindow.xaml

    /// </summary>

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }


        private void button1_Click(object sender, RoutedEventArgs e)

        {

            // 작업쓰레드 생성

            Task.Factory.StartNew(Run);            

        }


        private void Run()

        {

            // 해당 쓰레드가 UI쓰레드인가?

            if (textBox1.Dispatcher.CheckAccess())

            {

                //UI 쓰레드인 경우

                textBox1.Text = "Data";

            }

            else

            {

                // 작업쓰레드인 경우

                textBox1.Dispatcher.BeginInvoke(new Action(Run));

            }

        }

    }

}



3. more advanced way (more thinking)


public class Example

{

    // ...

    private async void NextMove_Click(object sender, RoutedEventArgs e)

    {

        await Task.Run(() => ComputeNextMove());

        // Update the UI with results

    }


    private async Task ComputeNextMove()

    {

        // ...

    }

    // ...

}


p.s. WinForm UI thread


using System;

using System.Windows.Forms;

using System.Threading;


namespace MultiThrdApp

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }


        private void btnQuery_Click(object sender, EventArgs e)

        {

            // 작업 쓰레드 시작

            Thread worker = new Thread(Run);

            worker.Start();

        }


        private void btnClear_Click(object sender, EventArgs e)

        {

            // UI 쓰레드에서 TextBox 갱신

            UpdateTextBox(string.Empty);

        }


        private void Run()

        { 

            // Long DB query

            Thread.Sleep(3000);

            string dbData = "Query Result";


            // 작업쓰레드에서 TextBox 갱신

            UpdateTextBox(dbData);

        }


        private void UpdateTextBox(string data)

        {

            // 호출한 쓰레드가 작업쓰레드인가?

            if (textBox1.InvokeRequired)

            {

                // 작업쓰레드인 경우

                textBox1.BeginInvoke(new Action(() => textBox1.Text = data));

            }

            else 

            {

                // UI 쓰레드인 경우

                textBox1.Text = data;

            }            

        }

    }

}



참고 URL : https://msdn.microsoft.com/ko-kr/library/windows/apps/hh994635.aspx

참고 URL : http://www.csharpstudy.com/Threads/uithread.aspx