Make dispatcher example to work

2019-09-06 16:55发布

I'm trying to make a working program from this example: http://msdn.microsoft.com/en-us/library/ms741870.aspx . I think I'm almost done, but I can't who shold be calling the Dispatcher : what should i use instead of tomorrow.Dispatcher.BeginInvoke ? I think I should put the UI thread, but how can i do that?

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";  
        }
    }
}

标签: c#
3条回答
啃猪蹄的小仙女
2楼-- · 2019-09-06 17:21

In Windows Forms you can just use this.BeginInvoke(...).

It is a method of Control class, and Form derives from Control.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-09-06 17:29

The problem is in the referencing, Dispatcher as introduced in .NET framework 3 and up is located in the System.Windows.Threading namespace and not in System.Threading .

The System.Windows namespace is available in WPF (Windows Presentation Foundation) projects.

查看更多
Luminary・发光体
4楼-- · 2019-09-06 17:31

How about this.Dispatcher.Invoke(...)?

查看更多
登录 后发表回答