简体   繁体   English

单击按钮时不按住按钮就可以运行C#的耗时方法

[英]C# run time consuming method on button click without keeping the button pressed

I do have experience with software developping in Python (GUI platform PyQt) and I am learing software development in C#. 我确实有使用Python(GUI平台PyQt)进行软件开发的经验,并且正在使用C#进行软件开发。 I wanted to know how can I run a thread/task in C# that uses UI objects but keeping the UI "alive" and not keeping the button pressed. 我想知道如何在使用UI对象的C#中运行线程/任务,但保持UI处于“活动状态”而不保持按下按钮的状态。 I did used "Invoke" method to share UI objects with thread/task and did not call any join method, but still button remain pressed during thread execution. 我确实使用“调用”方法与线程/任务共享UI对象,并且没有调用任何联接方法,但是在线程执行过程中仍然保持按下按钮的状态。 Is there any way to run this method in background, but keeping the GUI responsive? 有什么方法可以在后台运行此方法,但可以保持GUI响应速度?

Thanks in advance! 提前致谢!


private async void Button_Click(object sender, RoutedEventArgs e)
{
    await Task.Run(new Action(this.Iterate_balance));

}

private async void Iterate_balance()
{
    this.Dispatcher.Invoke(() =>
    {
        // the rest of code
    }
}

use async/await pattern properly and you won't need Dispatcher at all: 正确使用异步/等待模式,根本不需要Dispatcher:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    await Iterate_balance();    
}

private async Task Iterate_balance()
{
    button.Content = "Click to stop";

    // some long async operation
    await Task.Delay(TimeSpan.FromSeconds(4));

    button.Content = "Click to run";
}

TRY THIS: 尝试这个:

1.Add following using: using System.ComponentModel; 1.添加以下使用: using System.ComponentModel;

2.Declare background worker : 2.声明后台工作人员

private readonly BackgroundWorker worker = new BackgroundWorker();

3.Register events: 3.注册事件:

worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;

4.Implement two methods: 4.实现两种方法:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
   // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender, 
                                       RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete his work
}

5.Run worker async whenever your need. 5,在需要时随时运行worker异步。

worker.RunWorkerAsync();

Also if you want to report process progress you should subscribe to ProgressChanged event and use ReportProgress(Int32) in DoWork method to raise an event. 另外,如果要报告流程进度,则应订阅ProgressChanged事件并在DoWork方法中使用ReportProgress(Int32)引发事件。 Also set following: worker.WorkerReportsProgress = true; 还设置以下内容:worker.WorkerReportsProgress = true;

Hope this help. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM