如何逐个调用方法并在标签控件WPF中显示消息? [英] How to invoke methods one by one and display a message in label control WPF?

查看:85
本文介绍了如何逐个调用方法并在标签控件WPF中显示消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个接一个地执行3个方法,在执行每个方法的同时,应该在标签控件中显示一条消息(例如:检查method1 ..)。如何在WPF窗口中执行此操作。



UI线程不能等待工作线程完成,以显示窗口,工作线程应该一个接一个地执行。为此,我使用了join(),这使得UI线程也在等待工作线程完成。

解决方案

你需要在一个单独的线程中完成它。现在,问题是如何在UI中反映结果。您不能从非UI线程调用与UI相关的任何内容。相反,您需要使用 Invoke System.Windows.Threading的方法。 Dispatcher (对于Forms或WPF)或 System.Windows.Forms.Control (仅限表单)。



您将在我过去的答案中找到有关其工作原理和代码示例的详细说明:

Control.Invoke()与Control.BeginInvoke()

使用Treeview扫描仪和MD5的问题



另请参阅有关线程的更多参考资料:

主要的.NET事件线程

如何让keydown事件在不同的线程上运行i n vb.net

在启用禁用+多线程后控制事件未触发

主线程上的.NET事件 [ ^ ]。



-SA


< blockquote>为每个函数使用调度程序计时器



  public   class  ViewModel {

private static System.Timers.Timer aTimer;

public ViewModel()
{
aTimer = new Timer();
aTimer.Interval = 2000 ; // 每两秒

// 连接到已用事件
aTimer.Elapsed + = DoWork;

// 让计时器触发重复事件(默认为true)
aTimer.AutoReset = true ;

// 启动计时器
aTimer.Enabled = < span class =code-keyword> true ;
}

public void DoWork( Object source,System.Timers.ElapsedEventArgs e){
// 在这里工作
}
}


I want to execute 3 methods one after another, a message should be shown in label control (eg: checking method1..) at the same time when we execute each method. How to do this in WPF Window.

The UI thread must not wait for worker threads to complete, to show the window and the worker threads should execute one after another. For that purpose i have used join(), that made UI thread also waiting for worker threads to finish.

解决方案

You would need to do it in a separate thread. Now, the problem is how to reflect the results in a UI. You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke(),
Problem with Treeview Scanner And MD5.

See also more references on threading:
.NET event on main thread,
How to get a keydown event to operate on a different thread in vb.net,
Control events not firing after enable disable + multithreading,
.NET event on main thread[^].

—SA


Use dispatcher timer for every Function

public class ViewModel{

    private static System.Timers.Timer aTimer;

    public ViewModel()
    {
        aTimer = new Timer();
        aTimer.Interval = 2000; // every two seconds

        // Hookup to the elapsed event
        aTimer.Elapsed += DoWork;

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;
    }

    public void DoWork(Object source, System.Timers.ElapsedEventArgs e) {
        //do work here
    }
}


这篇关于如何逐个调用方法并在标签控件WPF中显示消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆