Skip to content

Instantly share code, notes, and snippets.

@Horusiath
Last active September 14, 2015 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Horusiath/895e22e32a4d009ee149 to your computer and use it in GitHub Desktop.
Save Horusiath/895e22e32a4d009ee149 to your computer and use it in GitHub Desktop.
Set of extensions (for missing methods) necessary for running Akka.NET < .NET 4.5
//-----------------------------------------------------------------------
// <copyright file="TaskExtensions.cs" company="Akka.NET Project">
// Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
// Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Net.Mime;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Akka.Util.Internal
{
public static class TaskExtensions
{
public static void CancelAfter(this CancellationTokenSource source, TimeSpan timeout)
{
var timer = new Timer(_ => source.Cancel());
timer.Change((int)timeout.TotalMilliseconds, -1);
}
public static Task<TResult> CastTask<TTask, TResult>(this Task<TTask> task)
{
if (task.IsCompleted)
return Tasks.FromResult((TResult) (object)task.Result);
var tcs = new TaskCompletionSource<TResult>();
if (task.IsFaulted)
tcs.SetException(task.Exception);
else
task.ContinueWith(_ =>
{
if (task.IsFaulted || task.Exception != null)
tcs.SetException(task.Exception);
else if (task.IsCanceled)
tcs.SetCanceled();
else
try
{
tcs.SetResult((TResult) (object) task.Result);
}
catch (Exception e)
{
tcs.SetException(e);
}
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
}
public static class Tasks
{
public static Task Done()
{
return FromResult<object>(null);
}
public static Task<TResult> FromResult<TResult>(TResult value)
{
var source = new TaskCompletionSource<TResult>();
source.SetResult(value);
return source.Task;
}
public static Task Delay(TimeSpan time)
{
var tcs = new TaskCompletionSource<object>();
var timer = new Timer(_ => tcs.TrySetResult(null));
timer.Change((int)time.TotalMilliseconds, -1);
return tcs.Task;
}
public static Task Delay(TimeSpan time, CancellationToken token)
{
var tcs = new TaskCompletionSource<object>();
token.Register(() => tcs.TrySetCanceled());
var timer = new Timer(_ => tcs.TrySetResult(null));
timer.Change((int)time.TotalMilliseconds, -1);
return tcs.Task;
}
public static Task<TResult> WhenAny<TResult>(IEnumerable<Task<TResult>> tasks)
{
var promise = new TaskCompletionSource<TResult>();
foreach (var task in tasks)
{
task.ContinueWith(t =>
{
if (t.IsCompleted)
{
promise.TrySetResult(t.Result);
}
});
}
return promise.Task;
}
public static Task WhenAny(IEnumerable<Task> tasks)
{
var promise = new TaskCompletionSource<object>();
foreach (var task in tasks)
{
task.ContinueWith(t =>
{
if (t.IsCompleted)
{
promise.TrySetResult(null);
}
});
}
return promise.Task;
}
}
/// <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 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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment