让调度员的例子工作

时间:2011-01-03 10:52:29

标签: c#

我正在尝试通过此示例制作一个有效的程序:http://msdn.microsoft.com/en-us/library/ms741870.aspx。我想我差不多完成了,但是我不能告诉他们  Dispatcher:我应该使用什么而不是明天.Dispatcher.BeginInvoke?我想我应该把UI线程,但我怎么能这样做?

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

namespace TestDelegate
{
    public partial class Form1 : Form
    {
        private delegate void NoArgDelegate();
        private delegate void OneArgDelegate(String arg);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Change the status image and start the rotation animation.
            button1.Enabled = false;
            button1.Text = "Contacting Server";

            // Start fetching the weather forecast asynchronously.
            NoArgDelegate fetcher = new NoArgDelegate(
                this.FetchWeatherFromServer);
            fetcher.BeginInvoke(null, null);
        }


        private void FetchWeatherFromServer()
        {
            Thread.Sleep(4000);        


            // Schedule the update function in the UI thread.
            tomorrow.Dispatcher.BeginInvoke(
                System.Threading.ThreadPriority.Normal,
                new OneArgDelegate(UpdateUserInterface), 
                weather);
        }

        private void UpdateUserInterface(String weather)
        {    
            //Update UI text
            button1.Enabled = true;
            button1.Text = "Fetch Forecast";  
        }
    }
}

3 个答案:

答案 0 :(得分:2)

在Windows窗体中,您只需使用this.BeginInvoke(...)

这是Control类的方法,而Form来自Control

答案 1 :(得分:1)

问题在于.NET Framework 3及更高版本中引用的引用Dispatcher 位于System.Windows.Threading命名空间,而不是System.Threading

System.Windows命名空间在WPF(Windows Presentation Foundation)项目中可用。

答案 2 :(得分:0)

this.Dispatcher.Invoke(...)怎么样?