如何通过任务线程而不是主线程抛出异常? [英] How do I throw exception by task thread instead of main thread?

查看:144
本文介绍了如何通过任务线程而不是主线程抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是演示wpf代码:

Here is the demo wpf code:

private CancellationTokenSource _cancel;

        public MainWindow()
        {
            InitializeComponent();

            _cancel = new CancellationTokenSource();
            var task = new Task(() =>
            {
                try
                {
                    _cancel.Token.Register(() =>
                    {
                        _cancel.Token.ThrowIfCancellationRequested();
                    });
                    Thread.Sleep(100000);
                }
                catch (Exception)
                {
                }
            });

            task.Start();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _cancel.Cancel();
        }





TaskCancel异常将抛出主线程,如何在任务线程中抛出TaskCancelException并且逮住?仍然通过点击按钮取消任务:)

谢谢!



The TaskCancel exception will throw in main thread, how can I do to throw TaskCancelException in the task thread and be catched? still cancel task by click button:)
Thanks!

推荐答案

,唯一的例外是你可以完全异步地进入一些工作线程thread是 System.Threading.ThreadAbortException ,由线程中止仅由运行时系统完成:

https://msdn.microsoft.com/en-us/library/system。 threading.threadabortexception%28v = vs.110%29.aspx [ ^ ],

https://msdn.microsoft.com/en-us/library/system.threading.thread.abort%28v=vs。 110%29.aspx [ ^ ]。



此技术与异常播种。



这种方法已经足够了,但我认为这很危险;我,作为一个了解它如何工作的人,使用它,但只是警告说使用它需要很好地理解你在做什么。请查看我过去的答案,

正确关闭dll中的线程 [ ^ ],

从专用线程创建进程的问题 [ ^ ]。



所有其他例外只能使用合作方法;它们应该被抛入同一个线程。为了理解原因,需要对异常机制有一些更深入的理解。请查看我过去的答案:

C#构造函数中的异常导致调用者分配失败? [ ^ ],

存储位置。操作系统中的网络异常 [ ^ ]。



这种合作方式的例子是系统的机制。 Threading.CancellationToken 你已经使用过:

https://msdn.microsoft.com/ en-us / library / system.threading.cancellationtoken%28v = vs.110%29.aspx [ ^ ],

https://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource% 28v = vs.110%29.aspx [ ^ ]。



您只需要从其他线程(主线程)请求取消,但异常被抛出在同一个应该被取消的线程中。请参阅上面引用的文章中的代码示例。



-SA
,The only exception you can seed into some working thread totally asynchronously to this thread is the System.Threading.ThreadAbortException, which is done only by runtime system as a result of thread abort:
https://msdn.microsoft.com/en-us/library/system.threading.threadabortexception%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.threading.thread.abort%28v=vs.110%29.aspx[^].

This technique is related to exception seeding.

This approach is quite adequate but is considered as dangerous my many; I, as a person who understands how it works under the hood, use it but would just warn that using it requires good understanding of what you are doing. Please see my past answers,
Close correcly the thread inside a dll[^],
Problem with creating Process from dedicated thread[^].

All other exceptions can only use cooperative approach; they should be thrown in the same thread. To, understand why, some deeper understanding of exception mechanism is needed. Please see my past answers:
Does Exception in C# Constructor Cause Caller Assignment to Fail?[^],
where was stored .net exceptions in operating system[^].

The example of such cooperative approach is the mechanism of System.Threading.CancellationToken you already use:
https://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource%28v=vs.110%29.aspx[^].

You only request the cancellation from some other thread (main thread), but exception is thrown in the same very thread which should be cancelled. Please see the code samples in the articles referenced above.

—SA


这篇关于如何通过任务线程而不是主线程抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆