【问题标题】:How to stop task and mouse cursor when having exception出现异常时如何停止任务和鼠标光标
【发布时间】:2014-03-27 14:26:32
【问题描述】:

我正在使用以下代码,问题是当我在 GetUserData() 中出现异常时 我收到消息给用户界面,当我把鼠标放在里面时,鼠标没有停止 鼠标 Cursors.Null 导致转储。 我的问题是:

  1. 当我遇到异常时如何停止任务 (tpl),即不继续 continueWith ?
  2. 出现异常时如何忽略鼠标光标?
Mouse.OverrideCursor = Cursors.Wait;
Task.Factory
    .StartNew(() =>
    {
        //-----get service Data ---------
        try
        {
            GetUsersData();
        }
        catch (Exception e)
        {
            _isValid = false;
            ThrowErrorMessage(e.Message);
             Mouse.OverrideCursor = Cursors.Null;
        }
    })
    .ContinueWith((task) =>
    {
        Mouse.OverrideCursor = null;
    }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

    isServiceValid = true;

【问题讨论】:

  • 为什么要使用ContinueWith 而不是async/await,你是否仅限于VS2010?否则,如果您需要面向 .NET 4.0 但使用 VS2012+ 进行开发,您仍然可以使用async/await,微软为此提供了Microsoft.Bcl.Async 库。

标签: c# wpf asynchronous task-parallel-library task


【解决方案1】:

您可以使用Task.Wait() 捕获异常。如果由于执行而出现异常,它将被重新抛出。

http://msdn.microsoft.com/en-us/library/dd997415%28v=vs.110%29.aspx

这篇文章很好地描述了这种行为。

到第二个问题:如果你想改变 Dispatcher 线程的 Cursor,你需要重新调用你的动作回到 Dispatcher:

Application.Current.Dispatcher.Invoke(new Action(() => Mouse.OverrideCursor = Cursors.Null));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 2011-05-26
    • 2013-02-15
    相关资源
    最近更新 更多