[英]C# run time consuming method on button click without keeping the button pressed
我確實有使用Python(GUI平台PyQt)進行軟件開發的經驗,並且正在使用C#進行軟件開發。 我想知道如何在使用UI對象的C#中運行線程/任務,但保持UI處於“活動狀態”而不保持按下按鈕的狀態。 我確實使用“調用”方法與線程/任務共享UI對象,並且沒有調用任何聯接方法,但是在線程執行過程中仍然保持按下按鈕的狀態。 有什么方法可以在后台運行此方法,但可以保持GUI響應速度?
提前致謝!
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
}
}
正確使用異步/等待模式,根本不需要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";
}
嘗試這個:
1.添加以下使用: using System.ComponentModel;
2.聲明后台工作人員 :
private readonly BackgroundWorker worker = new BackgroundWorker();
3.注冊事件:
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
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,在需要時隨時運行worker異步。
worker.RunWorkerAsync();
另外,如果要報告流程進度,則應訂閱ProgressChanged事件並在DoWork方法中使用ReportProgress(Int32)引發事件。 還設置以下內容:worker.WorkerReportsProgress = true;
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.