質問

I'm making a small program that will mostly present information from different sources, and I would need a constant loop in the background doing the hard work. But I can't press a button to get this information, it needs to run by itself.

I'm new to the whole WPF idea, and even though it feels neat with the whole XAML part, I'm still trying to adapt to the idea that the whole concept feels very event driven.

I've looked into the System.ComponentModel.BackgroundWorker class but it feels wrong since it's defined by DoWOrk and WorkComplete, and this will never be WorkComplete.

What is the proper way of executing background processing, avoiding user interaction ?

役に立ちましたか?

解決

I would suggest using System.Threading.Timer. Here some example code behind class which will update a label called timeLabel every second with current time:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.Loaded += MainWindow_Loaded;
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        Timer timer = new Timer(TimerElapsedHandler, null, 0, 1000);
    }

    private void TimerElapsedHandler(object state)
    {
        this.Dispatcher.Invoke(() => { timeLabel.Content = DateTime.Now.ToLongTimeString(); });
    }
}

You could also use some kind of BackgroundWorker/Task/whatever and have it execute something like the following in a separate thread:

while (...)
{
    this.Dispatcher.Invoke(() => { timeLabel.Content = DateTime.Now.ToLongTimeString(); });
    Thread.Sleep(1000);
}

他のヒント

BackgroundWorker also has a ReportProgress
Use the userState As Object to pass back information
It is an Object so you can pass anything you need to

BackgroundWorker.ReportProgress Method (Int32, Object)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top