using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;

namespace DispatcherExamples
{
    /// <summary>
    /// Interaction logic for MyWindow.xaml
    /// </summary>

    public partial class MyWindow : System.Windows.Window
    {

        public MyWindow()
        {
            InitializeComponent();

            useBeginInvokeButton.Click += new RoutedEventHandler(useBeginInvokeButton_Click);
        }

        void useBeginInvokeButton_Click(object sender, RoutedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                RunsOnWorkerThread();
            });
        }

        // Example C-2. Using Dispatcher.BeginInvoke

        public delegate void MyDelegateType();

        void RunsOnWorkerThread()
        {

            Color bgColor = CalculateBgColor();
            MyDelegateType methodForUiThread = delegate
            {
                this.Background = new SolidColorBrush(bgColor);
            };
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, methodForUiThread);
        }

        // End of Example C-2.

        static Random r = new Random();
        static Color CalculateBgColor()
        {
            byte[] colours = new byte[3];
            r.NextBytes(colours);
            return Color.FromRgb(colours[0], colours[1], colours[2]);
        }

    }
}