有ExceptionDispatchInfo的Microsoft.Bcl.Async模拟? [英] Is there an analog of ExceptionDispatchInfo in Microsoft.Bcl.Async?

查看:478
本文介绍了有ExceptionDispatchInfo的Microsoft.Bcl.Async模拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有的<中的模拟href=\"http://msdn.microsoft.com/en-us/library/system.runtime.exceptionservices.exceptiondispatchinfo%28v=vs.110%29.aspx\"相对=nofollow> ExceptionDispatchInfo 中的 Microsoft.Bcl.Async ?我找不到类似的事情。

Is there an analog of ExceptionDispatchInfo in Microsoft.Bcl.Async? I cannot find anything similar.

这问题已经由另一个问题矿。当异常的父任务可用,我可以使用 task.GetAwaiter()调用getResult()重新抛出,因为通过@StephenCleary建议。

This question was triggered by another question of mine. When the exception's parent task is available, I can use task.GetAwaiter().GetResult() to rethrow, as suggested by @StephenCleary.

什么是我的选择,当它不可?

What are my options for when it is not available?

推荐答案

我已经与AVO 提供的试验实施 - 但它没有通过所有的测试。我的意思是,它提供了基本的行为,但将在更复杂的情况下(如多重投掷,夺回等)失败。

I have experimented with the implementation provided by avo - yet it doesn't pass all the tests. By that I mean that it provides the basic behaviour but will fail in more complex cases (such as multiple throwing, recapturing, etc...).

Theraot.Core 我使这个类在这样的方式的背面端口它会在现代工作单,老单声道(pre * 2.6)和2.0任何的Microsoft .NET 4.0。

As part of Theraot.Core I have made a back port of this class in such way that it will work in modern Mono, old Mono (pre 2.6*) and any Microsoft .NET from 2.0 to 4.0.

*:从米格尔奥德伊卡萨一个小技巧:)

*: With a little tip from Miguel de Icaza :)

在code以下是目前仅在特性分支,它最终将移动到主分支(任务与沿.NET 2.0 :),此时它会提供通过的 Theraot.Core的NuGet 。我在这里把它留在万一有人需要它更早。

The code below is currently only on the Feature branch, it will eventually move to the master branch (along with Task for .NET 2.0 :), at which point it will available via the Theraot.Core nuget. I'm leaving it here in case somebody needs it sooner.

错误报告是在上项目的GitHub的(上面链接)问题跟踪的欢迎,如果您发现任何

Bug reports are welcome on the issue tracker at the project's github (linked above), if you find any.

#if NET20 || NET30 || NET35 || NET40

using System.Reflection;

namespace System.Runtime.ExceptionServices
{
    /// <summary>
    /// The ExceptionDispatchInfo object stores the stack trace information and Watson information that the exception contains at the point where it is captured. The exception can be thrown at another time and possibly on another thread by calling the ExceptionDispatchInfo.Throw method. The exception is thrown as if it had flowed from the point where it was captured to the point where the Throw method is called.
    /// </summary>
    public sealed class ExceptionDispatchInfo
    {
        private static FieldInfo _remoteStackTraceString;

        private Exception _exception;
        private object _stackTraceOriginal;
        private object _stackTrace;

        private ExceptionDispatchInfo(Exception exception)
        {
            _exception = exception;
            _stackTraceOriginal = _exception.StackTrace;
            _stackTrace = _exception.StackTrace;
            if (_stackTrace != null)
            {
                _stackTrace += Environment.NewLine + "---End of stack trace from previous location where exception was thrown ---" + Environment.NewLine;
            }
            else
            {
                _stackTrace = string.Empty;
            }
        }

        /// <summary>
        /// Creates an ExceptionDispatchInfo object that represents the specified exception at the current point in code.
        /// </summary>
        /// <param name="source">The exception whose state is captured, and which is represented by the returned object.</param>
        /// <returns>An object that represents the specified exception at the current point in code. </returns>
        public static ExceptionDispatchInfo Capture(Exception source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            return new ExceptionDispatchInfo(source);
        }

        /// <summary>
        /// Gets the exception that is represented by the current instance.
        /// </summary>
        public Exception SourceException
        {
            get
            {
                return _exception;
            }
        }

        private static FieldInfo GetFieldInfo()
        {
            if (_remoteStackTraceString == null)
            {
                // ---
                // Code by Miguel de Icaza

                FieldInfo remoteStackTraceString =
                    typeof(Exception).GetField("_remoteStackTraceString",
                    BindingFlags.Instance | BindingFlags.NonPublic); // MS.Net

                if (remoteStackTraceString == null)
                    remoteStackTraceString = typeof(Exception).GetField("remote_stack_trace",
                        BindingFlags.Instance | BindingFlags.NonPublic); // Mono pre-2.6

                // ---
                _remoteStackTraceString = remoteStackTraceString;
            }
            return _remoteStackTraceString;
        }

        private static void SetStackTrace(Exception exception, object value)
        {
            FieldInfo remoteStackTraceString = GetFieldInfo();
            remoteStackTraceString.SetValue(exception, value);
        }

        /// <summary>
        /// Throws the exception that is represented by the current ExceptionDispatchInfo object, after restoring the state that was saved when the exception was captured.
        /// </summary>
        public void Throw()
        {
            try
            {
                throw _exception;
            }
            catch (Exception exception)
            {
                GC.KeepAlive(exception);
                var newStackTrace = _stackTrace + BuildStackTrace(Environment.StackTrace);
                SetStackTrace(_exception, newStackTrace);
                throw;
            }
        }

        private string BuildStackTrace(string trace)
        {
            var items = trace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            var newStackTrace = new Text.StringBuilder();
            var found = false;
            foreach (var item in items)
            {
                // Only include lines that has files in the source code
                if (item.Contains(":"))
                {
                    if (item.Contains("System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()"))
                    {
                        // Stacktrace from here on will be added by the CLR
                        break;
                    }
                    if (found)
                    {
                        newStackTrace.Append(Environment.NewLine);
                    }
                    found = true;
                    newStackTrace.Append(item);
                }
                else if (found)
                {
                    break;
                }
            }
            var result = newStackTrace.ToString();
            return result;
        }
    }
}

#endif

这篇关于有ExceptionDispatchInfo的Microsoft.Bcl.Async模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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