相关疑难解决方法(0)

如何在wpf后台执行任务,同时能够提供报告并允许取消?

我想在点击一个wpf按钮后执行一个长时间运行的任务.这就是我做的.

private void Start(object sender, RoutedEventArgs e)
{
    for (int i = 0; i < 10; i++)
    {
        Thread.Sleep(2000); // simulate task
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,这会使wpf gui反应迟钝.我也想允许取消并每1秒报告一次进度.我扩展代码如下.

    DispatcherTimer dispatcherTimer = new DispatcherTimer(); // get progress every second
    private int progress = 0; // for progress reporting
    private bool isCancelled = false; // cancellation

    private void Start(object sender, RoutedEventArgs e)
    {
        InitializeTimer(); // initiallize interval timer 
        Start(10); // execute task
    }

    private void InitializeTimer()
    {
        dispatcherTimer.Tick += dispatcherTimer_Tick;
        dispatcherTimer.Interval = new TimeSpan(0,0,1); …
Run Code Online (Sandbox Code Playgroud)

c# wpf task-parallel-library

11
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×1

task-parallel-library ×1

wpf ×1