本文介绍了如何在WPF C#中显示进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hello Friends,
我想在WPF窗口显示进度条。
我希望点击更新其值一个按钮。
我已经尝试了后台工作者,但它没有用。
请帮助实现简单的方法,通过它我可以更新UI表格上的值/文本。
我现在有以下代码 -
Hello Friends,
I want to show progress bar on WPF Window.
and I want to update its value by click on one Button.
I have tried background worker but it is not is of no use.
Please help to implement simple method by which I can update values/texts on UI Form.
I have below code till now -
private void btn_Upload_Click(object sender, RoutedEventArgs e)
{
Proc_Bar.Value = 0;
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
testProcBar();
}
private void testProcBar()
{
Thread.Sleep(3000);
Proc_Bar.Value = Proc_Bar.Value + 1;
Thread.Sleep(3000);
Proc_Bar.Value = Proc_Bar.Value + 1;
Thread.Sleep(3000);
Proc_Bar.Value = Proc_Bar.Value + 1;
Thread.Sleep(3000);
Proc_Bar.Value = Proc_Bar.Value + 1;
Thread.Sleep(3000);
Proc_Bar.Value = Proc_Bar.Value + 1;
Thread.Sleep(3000);
Proc_Bar.Value = Proc_Bar.Value + 1;
Thread.Sleep(3000);
Proc_Bar.Value = Proc_Bar.Value + 1;
}
请帮助。!!!
Please help.!!!
推荐答案
private CancellationTokenSource _cancellation;
private async void Start_Click( object sender, RoutedEventArgs e )
{
if ( _cancellation != null )
{
_cancellation.Cancel( false );
_cancellation.Dispose();
}
_cancellation = new CancellationTokenSource();
try
{
Debug.WriteLine(
"Start_Click: My Thread id is {0}",
Thread.CurrentThread.ManagedThreadId );
// call it in another thread
await Task.Run(
() => AsyncUpdateProgressBar( _cancellation.Token ),
_cancellation.Token )
.ConfigureAwait( false );
// call it in same thread
//await AsyncUpdateProgressBar(_cancellation.Token);
}
catch ( TaskCanceledException )
{
// ignore
}
}
private async Task AsyncUpdateProgressBar( CancellationToken token )
{
Debug.WriteLine(
"AsyncUpdateProgressBar: My Thread id is {0}",
Thread.CurrentThread.ManagedThreadId );
for ( var i = 0; i <= 100 & !token.IsCancellationRequested; i++ )
{
// update value on dispatcher async
// this is necessary, when calling this method from another thread
// than the user interface thread!!!
var tempLocal = i;
await Dispatcher.InvokeAsync( () => Progress1.Value = tempLocal );
// wait a little while
await Task.Delay( 100, token );
}
}
private readonly SynchronizationContext context = null;
在构造函数中初始化:
initialize that in constructor :
this.context = SynchronizationContext.Current;
现在每当更新UI线程我们如下:
Now whenever update the UI Thread us it like below :
this.context.Send(x => Proc_Bar.Value = Proc_Bar.Value + 1;, null);
这可能有所帮助,试试这个。
This might help, try this.
这篇关于如何在WPF C#中显示进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!