Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@ -0,0 +1,101 @@
//
// System.Threading.AbandonedMutexException.cs
//
// Author:
// Dick Porter (dick@ximian.com)
//
// (C) Ximian, Inc. http://www.ximian.com
//
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
namespace System.Threading
{
[Serializable]
[ComVisible (false)]
public class AbandonedMutexException : SystemException
{
Mutex mutex;
int mutex_index = -1;
public AbandonedMutexException()
: base ("Mutex was abandoned")
{
}
public AbandonedMutexException (string message)
: base (message)
{
}
public AbandonedMutexException (int location, WaitHandle handle)
: base ("Mutex was abandoned")
{
mutex_index = location;
mutex = handle as Mutex;
}
protected AbandonedMutexException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
}
public AbandonedMutexException (string message, Exception inner)
: base (message, inner)
{
}
public AbandonedMutexException (string message, int location, WaitHandle handle)
: base (message)
{
mutex_index = location;
mutex = handle as Mutex;
}
public AbandonedMutexException (string message, Exception inner, int location, WaitHandle handle)
: base (message, inner)
{
mutex_index = location;
mutex = handle as Mutex;
}
public Mutex Mutex
{
get {
return(mutex);
}
}
public int MutexIndex
{
get {
return(mutex_index);
}
}
}
}

View File

@ -0,0 +1,44 @@
//
// System.Threading.ApartmentState.cs
//
// Author:
// Dick Porter (dick@ximian.com)
//
// (C) Ximian, Inc. http://www.ximian.com
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
namespace System.Threading
{
[ComVisible (true)]
[Serializable]
public enum ApartmentState {
STA = 0,
MTA = 1,
Unknown = 2
}
}

View File

@ -0,0 +1,115 @@
//
// System.Threading.AsyncFlowControl.cs
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Threading {
internal enum AsyncFlowControlType {
None,
Execution,
Security
}
public struct AsyncFlowControl : IDisposable {
private Thread _t;
private AsyncFlowControlType _type;
internal AsyncFlowControl (Thread t, AsyncFlowControlType type)
{
_t = t;
_type = type;
}
public void Undo ()
{
if (_t == null) {
throw new InvalidOperationException (Locale.GetText (
"Can only be called once."));
}
switch (_type) {
case AsyncFlowControlType.Execution:
ExecutionContext.RestoreFlow ();
break;
case AsyncFlowControlType.Security:
SecurityContext.RestoreFlow ();
break;
}
_t = null;
}
#if NET_4_0
public void Dispose ()
#else
void IDisposable.Dispose ()
#endif
{
if (_t != null) {
Undo ();
_t = null;
_type = AsyncFlowControlType.None;
}
}
public override int GetHashCode ()
{
return(base.GetHashCode ());
}
public override bool Equals (object obj)
{
if (!(obj is AsyncFlowControl)) {
return(false);
}
return(obj.Equals (this));
}
public bool Equals (AsyncFlowControl obj)
{
if (this._t == obj._t &&
this._type == obj._type) {
return(true);
} else {
return(false);
}
}
public static bool operator == (AsyncFlowControl a, AsyncFlowControl b)
{
return a.Equals (b);
}
public static bool operator != (AsyncFlowControl a, AsyncFlowControl b)
{
return !a.Equals (b);
}
}
}

View File

@ -0,0 +1,186 @@
// AtomicBoolean.cs
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
#if INSIDE_MONO_PARALLEL
using System.Threading;
namespace Mono.Threading
#else
namespace System.Threading
#endif
{
#if INSIDE_MONO_PARALLEL
public
#endif
struct AtomicBooleanValue
{
int flag;
const int UnSet = 0;
const int Set = 1;
public bool CompareAndExchange (bool expected, bool newVal)
{
int newTemp = newVal ? Set : UnSet;
int expectedTemp = expected ? Set : UnSet;
return Interlocked.CompareExchange (ref flag, newTemp, expectedTemp) == expectedTemp;
}
public static AtomicBooleanValue FromValue (bool value)
{
AtomicBooleanValue temp = new AtomicBooleanValue ();
temp.Value = value;
return temp;
}
public bool TrySet ()
{
return !Exchange (true);
}
public bool TryRelaxedSet ()
{
return flag == UnSet && !Exchange (true);
}
public bool Exchange (bool newVal)
{
int newTemp = newVal ? Set : UnSet;
return Interlocked.Exchange (ref flag, newTemp) == Set;
}
public bool Value {
get {
return flag == Set;
}
set {
Exchange (value);
}
}
public bool Equals (AtomicBooleanValue rhs)
{
return this.flag == rhs.flag;
}
public override bool Equals (object rhs)
{
return rhs is AtomicBooleanValue ? Equals ((AtomicBooleanValue)rhs) : false;
}
public override int GetHashCode ()
{
return flag.GetHashCode ();
}
public static explicit operator bool (AtomicBooleanValue rhs)
{
return rhs.Value;
}
public static implicit operator AtomicBooleanValue (bool rhs)
{
return AtomicBooleanValue.FromValue (rhs);
}
}
#if INSIDE_MONO_PARALLEL
public
#endif
class AtomicBoolean
{
int flag;
const int UnSet = 0;
const int Set = 1;
public bool CompareAndExchange (bool expected, bool newVal)
{
int newTemp = newVal ? Set : UnSet;
int expectedTemp = expected ? Set : UnSet;
return Interlocked.CompareExchange (ref flag, newTemp, expectedTemp) == expectedTemp;
}
public static AtomicBoolean FromValue (bool value)
{
AtomicBoolean temp = new AtomicBoolean ();
temp.Value = value;
return temp;
}
public bool TrySet ()
{
return !Exchange (true);
}
public bool TryRelaxedSet ()
{
return flag == UnSet && !Exchange (true);
}
public bool Exchange (bool newVal)
{
int newTemp = newVal ? Set : UnSet;
return Interlocked.Exchange (ref flag, newTemp) == Set;
}
public bool Value {
get {
return flag == Set;
}
set {
Exchange (value);
}
}
public bool Equals (AtomicBoolean rhs)
{
return this.flag == rhs.flag;
}
public override bool Equals (object rhs)
{
return rhs is AtomicBoolean ? Equals ((AtomicBoolean)rhs) : false;
}
public override int GetHashCode ()
{
return flag.GetHashCode ();
}
public static explicit operator bool (AtomicBoolean rhs)
{
return rhs.Value;
}
public static implicit operator AtomicBoolean (bool rhs)
{
return AtomicBoolean.FromValue (rhs);
}
}
}

View File

@ -0,0 +1,49 @@
//
// System.Threading.AutoResetEvent.cs
//
// Author:
// Dick Porter (dick@ximian.com)
// Veronica De Santis (veron78@interfree.it)
//
// (C) Ximian, Inc. http://www.ximian.com
//
//
// Copyright (C) 2004, 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Threading
{
[ComVisible (true)]
public sealed class AutoResetEvent : EventWaitHandle
{
// Constructor
public AutoResetEvent (bool initialState)
: base(initialState, EventResetMode.AutoReset)
{
}
}
}

View File

@ -0,0 +1,142 @@
//
// CancellationToken.cs
//
// Authors:
// Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (c) 2009 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if NET_4_0
using System;
using System.Threading;
using System.Diagnostics;
namespace System.Threading
{
[DebuggerDisplay ("IsCancellationRequested = {IsCancellationRequested}")]
public struct CancellationToken
{
readonly CancellationTokenSource source;
public CancellationToken (bool canceled)
: this (canceled ? CancellationTokenSource.CanceledSource : null)
{
}
internal CancellationToken (CancellationTokenSource source)
{
this.source = source;
}
public static CancellationToken None {
get {
// simply return new struct value, it's the fastest option
// and we don't have to bother with reseting source
return new CancellationToken ();
}
}
public CancellationTokenRegistration Register (Action callback)
{
return Register (callback, false);
}
public CancellationTokenRegistration Register (Action callback, bool useSynchronizationContext)
{
if (callback == null)
throw new ArgumentNullException ("callback");
return Source.Register (callback, useSynchronizationContext);
}
public CancellationTokenRegistration Register (Action<object> callback, object state)
{
return Register (callback, state, false);
}
public CancellationTokenRegistration Register (Action<object> callback, object state, bool useSynchronizationContext)
{
if (callback == null)
throw new ArgumentNullException ("callback");
return Register (() => callback (state), useSynchronizationContext);
}
public void ThrowIfCancellationRequested ()
{
if (source != null && source.IsCancellationRequested)
throw new OperationCanceledException (this);
}
public bool Equals (CancellationToken other)
{
return this.Source == other.Source;
}
public override bool Equals (object other)
{
return (other is CancellationToken) ? Equals ((CancellationToken)other) : false;
}
public override int GetHashCode ()
{
return Source.GetHashCode ();
}
public static bool operator == (CancellationToken left, CancellationToken right)
{
return left.Equals (right);
}
public static bool operator != (CancellationToken left, CancellationToken right)
{
return !left.Equals (right);
}
public bool CanBeCanceled {
get {
return source != null;
}
}
public bool IsCancellationRequested {
get {
return Source.IsCancellationRequested;
}
}
public WaitHandle WaitHandle {
get {
return Source.WaitHandle;
}
}
CancellationTokenSource Source {
get {
return source ?? CancellationTokenSource.NoneSource;
}
}
}
}
#endif

View File

@ -0,0 +1,80 @@
//
// CancellationTokenRegistration.cs
//
// Author:
// Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
//
// Copyright (c) 2009 Jérémie "Garuma" Laval
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if NET_4_0
using System;
using System.Threading;
namespace System.Threading
{
public struct CancellationTokenRegistration: IDisposable, IEquatable<CancellationTokenRegistration>
{
int id;
CancellationTokenSource source;
internal CancellationTokenRegistration (int id, CancellationTokenSource source)
{
this.id = id;
this.source = source;
}
#region IDisposable implementation
public void Dispose ()
{
if (source != null)
source.RemoveCallback (this);
}
#endregion
#region IEquatable<CancellationTokenRegistration> implementation
public bool Equals (CancellationTokenRegistration other)
{
return this.id == other.id && this.source == other.source;
}
public static bool operator== (CancellationTokenRegistration left, CancellationTokenRegistration right)
{
return left.Equals (right);
}
public static bool operator!= (CancellationTokenRegistration left, CancellationTokenRegistration right)
{
return !left.Equals (right);
}
#endregion
public override int GetHashCode ()
{
return id.GetHashCode () ^ (source == null ? 0 : source.GetHashCode ());
}
public override bool Equals (object obj)
{
return (obj is CancellationTokenRegistration) ? Equals ((CancellationTokenRegistration)obj) : false;
}
}
}
#endif

View File

@ -0,0 +1,322 @@
//
// CancellationTokenSource.cs
//
// Authors:
// Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (c) 2009 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if NET_4_0
using System.Collections.Generic;
using System.Collections.Concurrent;
namespace System.Threading
{
#if !NET_4_5
sealed
#endif
public class CancellationTokenSource : IDisposable
{
const int StateValid = 0;
const int StateCanceled = 1 << 1;
const int StateDisposed = 1 << 2;
int state;
int currId = int.MinValue;
ConcurrentDictionary<CancellationTokenRegistration, Action> callbacks;
CancellationTokenRegistration[] linkedTokens;
ManualResetEvent handle;
internal static readonly CancellationTokenSource NoneSource = new CancellationTokenSource ();
internal static readonly CancellationTokenSource CanceledSource = new CancellationTokenSource ();
#if NET_4_5
static readonly TimerCallback timer_callback;
Timer timer;
#endif
static CancellationTokenSource ()
{
CanceledSource.state = StateCanceled;
#if NET_4_5
timer_callback = token => {
var cts = (CancellationTokenSource) token;
cts.CancelSafe ();
};
#endif
}
public CancellationTokenSource ()
{
callbacks = new ConcurrentDictionary<CancellationTokenRegistration, Action> ();
handle = new ManualResetEvent (false);
}
#if NET_4_5
public CancellationTokenSource (int millisecondsDelay)
: this ()
{
if (millisecondsDelay < -1)
throw new ArgumentOutOfRangeException ("millisecondsDelay");
if (millisecondsDelay != Timeout.Infinite)
timer = new Timer (timer_callback, this, millisecondsDelay, Timeout.Infinite);
}
public CancellationTokenSource (TimeSpan delay)
: this (CheckTimeout (delay))
{
}
#endif
public CancellationToken Token {
get {
CheckDisposed ();
return new CancellationToken (this);
}
}
public bool IsCancellationRequested {
get {
return (state & StateCanceled) != 0;
}
}
internal WaitHandle WaitHandle {
get {
CheckDisposed ();
return handle;
}
}
public void Cancel ()
{
Cancel (false);
}
// If parameter is true we throw exception as soon as they appear otherwise we aggregate them
public void Cancel (bool throwOnFirstException)
{
CheckDisposed ();
Cancellation (throwOnFirstException);
}
//
// Don't throw ObjectDisposedException if the callback
// is called concurrently with a Dispose
//
void CancelSafe ()
{
if (state == StateValid)
Cancellation (true);
}
void Cancellation (bool throwOnFirstException)
{
if (Interlocked.CompareExchange (ref state, StateCanceled, StateValid) != StateValid)
return;
handle.Set ();
if (linkedTokens != null)
UnregisterLinkedTokens ();
var cbs = callbacks;
if (cbs == null)
return;
List<Exception> exceptions = null;
try {
Action cb;
for (int id = currId; id != int.MinValue; id--) {
if (!cbs.TryRemove (new CancellationTokenRegistration (id, this), out cb))
continue;
if (cb == null)
continue;
if (throwOnFirstException) {
cb ();
} else {
try {
cb ();
} catch (Exception e) {
if (exceptions == null)
exceptions = new List<Exception> ();
exceptions.Add (e);
}
}
}
} finally {
cbs.Clear ();
}
if (exceptions != null)
throw new AggregateException (exceptions);
}
#if NET_4_5
public void CancelAfter (TimeSpan delay)
{
CancelAfter (CheckTimeout (delay));
}
public void CancelAfter (int millisecondsDelay)
{
if (millisecondsDelay < -1)
throw new ArgumentOutOfRangeException ("millisecondsDelay");
CheckDisposed ();
if (IsCancellationRequested || millisecondsDelay == Timeout.Infinite)
return;
if (timer == null) {
// Have to be carefull not to create secondary background timer
var t = new Timer (timer_callback, this, Timeout.Infinite, Timeout.Infinite);
if (Interlocked.CompareExchange (ref timer, t, null) != null)
t.Dispose ();
}
timer.Change (millisecondsDelay, Timeout.Infinite);
}
#endif
public static CancellationTokenSource CreateLinkedTokenSource (CancellationToken token1, CancellationToken token2)
{
return CreateLinkedTokenSource (new [] { token1, token2 });
}
public static CancellationTokenSource CreateLinkedTokenSource (params CancellationToken[] tokens)
{
if (tokens == null)
throw new ArgumentNullException ("tokens");
if (tokens.Length == 0)
throw new ArgumentException ("Empty tokens array");
CancellationTokenSource src = new CancellationTokenSource ();
Action action = src.CancelSafe;
var registrations = new List<CancellationTokenRegistration> (tokens.Length);
foreach (CancellationToken token in tokens) {
if (token.CanBeCanceled)
registrations.Add (token.Register (action));
}
src.linkedTokens = registrations.ToArray ();
return src;
}
static int CheckTimeout (TimeSpan delay)
{
try {
return checked ((int) delay.TotalMilliseconds);
} catch (OverflowException) {
throw new ArgumentOutOfRangeException ("delay");
}
}
void CheckDisposed ()
{
if ((state & StateDisposed) != 0)
throw new ObjectDisposedException (GetType ().Name);
}
public void Dispose ()
{
Dispose (true);
}
#if NET_4_5
protected virtual
#endif
void Dispose (bool disposing)
{
if (disposing && (state & StateDisposed) == 0) {
if (Interlocked.CompareExchange (ref state, StateDisposed, StateValid) == StateValid) {
UnregisterLinkedTokens ();
callbacks = null;
} else {
if (handle != null)
handle.WaitOne ();
state |= StateDisposed;
Thread.MemoryBarrier ();
}
#if NET_4_5
if (timer != null)
timer.Dispose ();
#endif
handle.Dispose ();
handle = null;
}
}
void UnregisterLinkedTokens ()
{
var registrations = Interlocked.Exchange (ref linkedTokens, null);
if (registrations == null)
return;
foreach (var linked in registrations)
linked.Dispose ();
}
internal CancellationTokenRegistration Register (Action callback, bool useSynchronizationContext)
{
CheckDisposed ();
var tokenReg = new CancellationTokenRegistration (Interlocked.Increment (ref currId), this);
/* If the source is already canceled we execute the callback immediately
* if not, we try to add it to the queue and if it is currently being processed
* we try to execute it back ourselves to be sure the callback is ran
*/
if (IsCancellationRequested)
callback ();
else {
callbacks.TryAdd (tokenReg, callback);
if (IsCancellationRequested && callbacks.TryRemove (tokenReg, out callback))
callback ();
}
return tokenReg;
}
internal void RemoveCallback (CancellationTokenRegistration reg)
{
// Ignore call if the source has been disposed
if ((state & StateDisposed) != 0)
return;
Action dummy;
var cbs = callbacks;
if (cbs != null)
cbs.TryRemove (reg, out dummy);
}
}
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,166 @@
//
// System.Threading.Thread.cs
//
// Authors:
// Zoltan Varga (vargaz@freemail.hu)
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
namespace System.Threading {
[Serializable]
public sealed class CompressedStack : ISerializable {
private ArrayList _list;
internal CompressedStack (int length)
{
if (length > 0)
_list = new ArrayList (length);
}
internal CompressedStack (CompressedStack cs)
{
if ((cs != null) && (cs._list != null))
_list = (ArrayList) cs._list.Clone ();
}
[ComVisibleAttribute (false)]
public CompressedStack CreateCopy ()
{
return new CompressedStack (this);
}
public static CompressedStack Capture ()
{
CompressedStack cs = new CompressedStack (0);
cs._list = SecurityFrame.GetStack (1);
// include any current CompressedStack inside the new Capture
CompressedStack currentCs = Thread.CurrentThread.GetCompressedStack ();
if (currentCs != null) {
for (int i=0; i < currentCs._list.Count; i++)
cs._list.Add (currentCs._list [i]);
}
return cs;
}
// NOTE: This method doesn't show in the class library status page because
// it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
// But it's there!
#if NET_4_0
[SecurityCritical]
#else
[SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
[StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
#endif
static public CompressedStack GetCompressedStack ()
{
// Note: CompressedStack.GetCompressedStack doesn't return null
// like Thread.CurrentThread.GetCompressedStack if no compressed
// stack is present.
CompressedStack cs = Thread.CurrentThread.GetCompressedStack ();
if (cs == null) {
cs = CompressedStack.Capture ();
} else {
// merge the existing compressed stack (from a previous Thread) with the current
// Thread stack so we can assign "all of it" to yet another Thread
CompressedStack newstack = CompressedStack.Capture ();
for (int i=0; i < newstack._list.Count; i++)
cs._list.Add (newstack._list [i]);
}
return cs;
}
[MonoTODO ("incomplete")]
#if NET_4_0
[SecurityCritical]
#else
[ReflectionPermission (SecurityAction.Demand, MemberAccess = true)]
#endif
public void GetObjectData (SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException ("info");
}
#if NET_4_0
[SecurityCritical]
#else
[SecurityPermission (SecurityAction.LinkDemand, Infrastructure = true)]
#endif
static public void Run (CompressedStack compressedStack, ContextCallback callback, object state)
{
if (compressedStack == null)
throw new ArgumentException ("compressedStack");
Thread t = Thread.CurrentThread;
CompressedStack original = null;
try {
original = t.GetCompressedStack ();
t.SetCompressedStack (compressedStack);
callback (state);
}
finally {
if (original != null)
t.SetCompressedStack (original);
}
}
// internal stuff
internal bool Equals (CompressedStack cs)
{
if (IsEmpty ())
return cs.IsEmpty ();
if (cs.IsEmpty ())
return false;
if (_list.Count != cs._list.Count)
return false;
for (int i=0; i < _list.Count; i++) {
SecurityFrame sf1 = (SecurityFrame) _list [i];
SecurityFrame sf2 = (SecurityFrame) cs._list [i];
if (!sf1.Equals (sf2))
return false;
}
return true;
}
internal bool IsEmpty ()
{
return ((_list == null) || (_list.Count == 0));
}
internal IList List {
get { return _list; }
}
}
}

View File

@ -0,0 +1,36 @@
//
// System.Threading.ContextCallback delegate
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
namespace System.Threading {
[ComVisible (true)]
public delegate void ContextCallback (object state);
}

View File

@ -0,0 +1,211 @@
// CountdownEvent.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin Inc (http://www.xamarin.com).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
#if NET_4_0
namespace System.Threading
{
[System.Diagnostics.DebuggerDisplayAttribute ("Initial Count={InitialCount}, Current Count={CurrentCount}")]
public class CountdownEvent : IDisposable
{
int initialCount;
int initial;
ManualResetEventSlim evt;
public CountdownEvent (int initialCount)
{
if (initialCount < 0)
throw new ArgumentOutOfRangeException ("initialCount");
evt = new ManualResetEventSlim (initialCount == 0);
this.initial = this.initialCount = initialCount;
}
public int CurrentCount {
get {
return initialCount;
}
}
public int InitialCount {
get {
return initial;
}
}
public bool IsSet {
get {
return initialCount == 0;
}
}
public WaitHandle WaitHandle {
get {
return evt.WaitHandle;
}
}
public bool Signal ()
{
return Signal (1);
}
public bool Signal (int signalCount)
{
if (signalCount <= 0)
throw new ArgumentOutOfRangeException ("signalCount");
CheckDisposed ();
int newValue;
if (!ApplyOperation (-signalCount, out newValue))
throw new InvalidOperationException ("The event is already set");
if (newValue == 0) {
evt.Set ();
return true;
}
return false;
}
public void AddCount ()
{
AddCount (1);
}
public void AddCount (int signalCount)
{
if (!TryAddCount (signalCount))
throw new InvalidOperationException ("The event is already signaled and cannot be incremented");
}
public bool TryAddCount ()
{
return TryAddCount (1);
}
public bool TryAddCount (int signalCount)
{
if (signalCount <= 0)
throw new ArgumentOutOfRangeException ("signalCount");
CheckDisposed ();
int temp;
return ApplyOperation (signalCount, out temp);
}
bool ApplyOperation (int num, out int newValue)
{
int oldCount;
do {
oldCount = initialCount;
if (oldCount == 0) {
newValue = 0;
return false;
}
newValue = oldCount + num;
if (newValue < 0)
return false;
} while (Interlocked.CompareExchange (ref initialCount, newValue, oldCount) != oldCount);
return true;
}
public void Wait ()
{
evt.Wait ();
}
public void Wait (CancellationToken cancellationToken)
{
evt.Wait (cancellationToken);
}
public bool Wait (int millisecondsTimeout)
{
return evt.Wait (millisecondsTimeout);
}
public bool Wait(TimeSpan timeout)
{
return evt.Wait (timeout);
}
public bool Wait (int millisecondsTimeout, CancellationToken cancellationToken)
{
return evt.Wait (millisecondsTimeout, cancellationToken);
}
public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
{
return evt.Wait (timeout, cancellationToken);
}
public void Reset ()
{
Reset (initial);
}
public void Reset (int count)
{
if (count < 0)
throw new ArgumentOutOfRangeException ("count");
CheckDisposed ();
initialCount = initial = count;
if (count == 0)
evt.Set ();
else
evt.Reset ();
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing)
evt.Dispose ();
}
void CheckDisposed ()
{
if (evt.disposed.Value)
throw new ObjectDisposedException ("CountdownEvent");
}
}
}
#endif

View File

@ -0,0 +1,42 @@
// EventResetMode.cs
//
// Author:
// Dick Porter (dick@ximian.com)
//
// (C) Ximian, Inc. http://www.ximian.com
//
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
namespace System.Threading
{
[ComVisible (false)]
public enum EventResetMode
{
AutoReset = 0,
ManualReset = 1,
}
}

View File

@ -0,0 +1,221 @@
//
// System.Threading.EventWaitHandle.cs
//
// Author:
// Dick Porter (dick@ximian.com)
//
// (C) Ximian, Inc. (http://www.ximian.com)
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
namespace System.Threading
{
[ComVisible (true)]
public class EventWaitHandle : WaitHandle
{
private EventWaitHandle (IntPtr handle)
{
Handle = handle;
}
static bool IsManualReset (EventResetMode mode)
{
if ((mode < EventResetMode.AutoReset) || (mode > EventResetMode.ManualReset))
throw new ArgumentException ("mode");
return (mode == EventResetMode.ManualReset);
}
public EventWaitHandle (bool initialState, EventResetMode mode)
{
bool created;
bool manual = IsManualReset (mode);
Handle = NativeEventCalls.CreateEvent_internal (manual, initialState, null, out created);
}
#if !MOBILE
public EventWaitHandle (bool initialState, EventResetMode mode,
string name)
{
bool created;
bool manual = IsManualReset (mode);
Handle = NativeEventCalls.CreateEvent_internal (manual, initialState, name, out created);
}
public EventWaitHandle (bool initialState, EventResetMode mode,
string name, out bool createdNew)
{
bool manual = IsManualReset (mode);
Handle = NativeEventCalls.CreateEvent_internal (manual, initialState, name, out createdNew);
}
[MonoTODO ("Use access control in CreateEvent_internal")]
public EventWaitHandle (bool initialState, EventResetMode mode,
string name, out bool createdNew,
EventWaitHandleSecurity eventSecurity)
{
bool manual = IsManualReset (mode);
Handle = NativeEventCalls.CreateEvent_internal (manual, initialState, name, out createdNew);
}
public EventWaitHandleSecurity GetAccessControl ()
{
return new EventWaitHandleSecurity (SafeWaitHandle,
AccessControlSections.Owner |
AccessControlSections.Group |
AccessControlSections.Access);
}
public static EventWaitHandle OpenExisting (string name)
{
return(OpenExisting (name, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify));
}
public static EventWaitHandle OpenExisting (string name, EventWaitHandleRights rights)
{
if (name == null) {
throw new ArgumentNullException ("name");
}
if ((name.Length == 0) ||
(name.Length > 260)) {
throw new ArgumentException ("name", Locale.GetText ("Invalid length [1-260]."));
}
MonoIOError error;
IntPtr handle = NativeEventCalls.OpenEvent_internal (name, rights, out error);
if (handle == (IntPtr)null) {
if (error == MonoIOError.ERROR_FILE_NOT_FOUND) {
throw new WaitHandleCannotBeOpenedException (Locale.GetText ("Named Event handle does not exist: ") + name);
} else if (error == MonoIOError.ERROR_ACCESS_DENIED) {
throw new UnauthorizedAccessException ();
} else {
throw new IOException (Locale.GetText ("Win32 IO error: ") + error.ToString ());
}
}
return(new EventWaitHandle (handle));
}
public static bool TryOpenExisting (string name, out EventWaitHandle result)
{
return TryOpenExisting (
name, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, out result);
}
public static bool TryOpenExisting (string name, EventWaitHandleRights rights,
out EventWaitHandle result)
{
if (name == null) {
throw new ArgumentNullException ("name");
}
if ((name.Length == 0) || (name.Length > 260)) {
throw new ArgumentException ("name", Locale.GetText ("Invalid length [1-260]."));
}
MonoIOError error;
IntPtr handle = NativeEventCalls.OpenEvent_internal (name, rights, out error);
if (handle == (IntPtr)null) {
result = null;
return false;
}
result = new EventWaitHandle (handle);
return true;
}
#else
public EventWaitHandle (bool initialState, EventResetMode mode, string name)
{
throw new NotSupportedException ();
}
public EventWaitHandle (bool initialState, EventResetMode mode,
string name, out bool createdNew)
{
throw new NotSupportedException ();
}
public EventWaitHandle (bool initialState, EventResetMode mode,
string name, out bool createdNew,
EventWaitHandleSecurity eventSecurity)
{
throw new NotSupportedException ();
}
public static EventWaitHandle OpenExisting (string name)
{
throw new NotSupportedException ();
}
public static EventWaitHandle OpenExisting (string name, EventWaitHandleRights rights)
{
throw new NotSupportedException ();
}
public static bool TryOpenExisting (string name, out EventWaitHandle result)
{
throw new NotSupportedException ();
}
public static bool TryOpenExisting (string name, EventWaitHandleRights rights,
out EventWaitHandle result)
{
throw new NotSupportedException ();
}
#endif
public bool Reset ()
{
/* This needs locking since another thread could dispose the handle */
lock (this) {
CheckDisposed ();
return (NativeEventCalls.ResetEvent_internal (Handle));
}
}
public bool Set ()
{
lock (this) {
CheckDisposed ();
return (NativeEventCalls.SetEvent_internal (Handle));
}
}
#if !NET_2_1
public void SetAccessControl (EventWaitHandleSecurity eventSecurity)
{
if (null == eventSecurity)
throw new ArgumentNullException ("eventSecurity");
eventSecurity.PersistModifications (SafeWaitHandle);
}
#endif
}
}

View File

@ -0,0 +1,236 @@
//
// System.Threading.ExecutionContext.cs
//
// Authors:
// Lluis Sanchez (lluis@novell.com)
// Sebastien Pouliot <sebastien@ximian.com>
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
// Copyright (C) 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Runtime.Remoting.Messaging;
using System.Collections.Generic;
namespace System.Threading {
[Serializable]
public sealed class ExecutionContext : ISerializable
#if NET_4_0
, IDisposable
#endif
{
#if !MOBILE
private SecurityContext _sc;
#endif
private LogicalCallContext _lcc;
private bool _suppressFlow;
private bool _capture;
Dictionary<string, object> local_data;
internal ExecutionContext ()
{
}
private ExecutionContext (ExecutionContext ec)
{
#if !MOBILE
if (ec._sc != null)
_sc = new SecurityContext (ec._sc);
#endif
if (ec._lcc != null)
_lcc = (LogicalCallContext) ec._lcc.Clone ();
_suppressFlow = ec._suppressFlow;
_capture = true;
}
[MonoTODO]
internal ExecutionContext (SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException ();
}
public static ExecutionContext Capture ()
{
return Capture (true, false);
}
internal static ExecutionContext Capture (bool captureSyncContext, bool nullOnEmpty)
{
ExecutionContext ec = Current;
if (ec.FlowSuppressed)
return null;
if (nullOnEmpty
#if !MOBILE
&& ec._sc == null
#endif
&& (ec._lcc == null || !ec._lcc.HasInfo))
return null;
ExecutionContext capture = new ExecutionContext (ec);
#if !MOBILE
if (SecurityManager.SecurityEnabled)
capture.SecurityContext = SecurityContext.Capture ();
#endif
return capture;
}
public ExecutionContext CreateCopy ()
{
if (!_capture)
throw new InvalidOperationException ();
return new ExecutionContext (this);
}
#if NET_4_0
public void Dispose ()
{
#if !MOBILE
if (_sc != null)
_sc.Dispose ();
#endif
}
#endif
[MonoTODO]
[ReflectionPermission (SecurityAction.Demand, MemberAccess = true)]
public void GetObjectData (SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException ("info");
throw new NotImplementedException ();
}
// internal stuff
internal LogicalCallContext LogicalCallContext {
get {
if (_lcc == null)
_lcc = new LogicalCallContext ();
return _lcc;
}
set {
_lcc = value;
}
}
internal Dictionary<string, object> DataStore {
get {
if (local_data == null)
local_data = new Dictionary<string, object> ();
return local_data;
}
set {
local_data = value;
}
}
#if !MOBILE
internal SecurityContext SecurityContext {
get {
if (_sc == null)
_sc = new SecurityContext ();
return _sc;
}
set { _sc = value; }
}
#endif
internal bool FlowSuppressed {
get { return _suppressFlow; }
set { _suppressFlow = value; }
}
public static bool IsFlowSuppressed ()
{
return Current.FlowSuppressed;
}
public static void RestoreFlow ()
{
ExecutionContext ec = Current;
if (!ec.FlowSuppressed)
throw new InvalidOperationException ();
ec.FlowSuppressed = false;
}
[SecurityPermission (SecurityAction.LinkDemand, Infrastructure = true)]
public static void Run (ExecutionContext executionContext, ContextCallback callback, object state)
{
if (executionContext == null) {
throw new InvalidOperationException (Locale.GetText (
"Null ExecutionContext"));
}
var prev = Current;
try {
Thread.CurrentThread.ExecutionContext = executionContext;
callback (state);
} finally {
Thread.CurrentThread.ExecutionContext = prev;
}
}
public static AsyncFlowControl SuppressFlow ()
{
Thread t = Thread.CurrentThread;
t.ExecutionContext.FlowSuppressed = true;
return new AsyncFlowControl (t, AsyncFlowControlType.Execution);
}
internal static LogicalCallContext CreateLogicalCallContext (bool createEmpty)
{
var lcc = Current._lcc;
if (lcc == null) {
if (createEmpty)
lcc = new LogicalCallContext ();
return lcc;
}
return (LogicalCallContext) lcc.Clone ();
}
internal void FreeNamedDataSlot (string name)
{
if (_lcc != null)
_lcc.FreeNamedDataSlot (name);
if (local_data != null)
local_data.Remove (name);
}
internal static ExecutionContext Current {
get {
return Thread.CurrentThread.ExecutionContext;
}
}
}
}

View File

@ -0,0 +1,56 @@
//
// System.Threading.HostExecutionContext class
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace System.Threading {
[MonoTODO ("Useless until the runtime supports it")]
public class HostExecutionContext {
private object _state;
public HostExecutionContext ()
{
_state = null;
}
public HostExecutionContext (object state)
{
_state = state;
}
public virtual HostExecutionContext CreateCopy ()
{
return new HostExecutionContext (_state);
}
protected internal object State {
get { return _state; }
set { _state = value; }
}
}
}

View File

@ -0,0 +1,61 @@
//
// System.Threading.HostExecutionContextManager class
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
namespace System.Threading {
public class HostExecutionContextManager {
public HostExecutionContextManager ()
{
}
[MonoTODO]
public virtual HostExecutionContext Capture ()
{
throw new NotImplementedException ();
}
[MonoTODO]
[ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
public virtual void Revert (object previousState)
{
throw new NotImplementedException ();
}
[MonoTODO]
[SecurityPermission (SecurityAction.LinkDemand, Infrastructure = true)]
public virtual object SetHostExecutionContext (HostExecutionContext hostExecutionContext)
{
throw new NotImplementedException ();
}
}
}

View File

@ -0,0 +1,42 @@
//
// System.Threading.IOCompletionCallback.cs
//
// Author:
// Dick Porter (dick@ximian.com)
//
// (C) Ximian, Inc. http://www.ximian.com
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
namespace System.Threading
{
// 'unsafe' wasn't in the spec, but the compiler insists because of
// the pointer.
[ComVisible (true)]
[CLSCompliant(false)]
public unsafe delegate void IOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped *pOVERLAP);
}

View File

@ -0,0 +1,127 @@
//
// System.Threading.Interlocked.cs
//
// Author:
// Patrik Torstensson (patrik.torstensson@labs2.com)
// Dick Porter (dick@ximian.com)
//
// (C) Ximian, Inc. http://www.ximian.com
//
//
// Copyright (C) 2004, 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
namespace System.Threading
{
public static class Interlocked
{
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static int CompareExchange(ref int location1, int value, int comparand);
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static object CompareExchange(ref object location1, object value, object comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static float CompareExchange(ref float location1, float value, float comparand);
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static int Decrement(ref int location);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static long Decrement(ref long location);
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static int Increment(ref int location);
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static long Increment(ref long location);
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static int Exchange(ref int location1, int value);
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static object Exchange(ref object location1, object value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static float Exchange(ref float location1, float value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static long CompareExchange(ref long location1, long value, long comparand);
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static IntPtr CompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static double CompareExchange(ref double location1, double value, double comparand);
[ComVisible (false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
public extern static T CompareExchange<T> (ref T location1, T value, T comparand) where T:class;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static long Exchange(ref long location1, long value);
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static IntPtr Exchange(ref IntPtr location1, IntPtr value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static double Exchange(ref double location1, double value);
[ComVisible (false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
public extern static T Exchange<T> (ref T location1, T value) where T:class;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static long Read(ref long location);
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static int Add(ref int location1, int value);
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static long Add(ref long location1, long value);
#if NET_4_5
public static void MemoryBarrier () {
Thread.MemoryBarrier ();
}
#endif
}
}

View File

@ -0,0 +1,89 @@
//
// LazyInitializer.cs
//
// Authors:
// Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (c) 2009 Jérémie "Garuma" Laval
// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if NET_4_0
namespace System.Threading
{
public static class LazyInitializer
{
public static T EnsureInitialized<T> (ref T target) where T : class
{
return target ?? EnsureInitialized (ref target, GetDefaultCtorValue<T>);
}
public static T EnsureInitialized<T> (ref T target, Func<T> valueFactory) where T : class
{
if (target == null) {
var value = valueFactory ();
if (value == null)
throw new InvalidOperationException ();
Interlocked.CompareExchange (ref target, value, null);
}
return target;
}
public static T EnsureInitialized<T> (ref T target, ref bool initialized, ref object syncLock)
{
return EnsureInitialized (ref target, ref initialized, ref syncLock, GetDefaultCtorValue<T>);
}
public static T EnsureInitialized<T> (ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
{
if (initialized)
return target;
if (syncLock == null)
Interlocked.CompareExchange (ref syncLock, new object (), null);
lock (syncLock) {
if (initialized)
return target;
initialized = true;
Thread.MemoryBarrier ();
target = valueFactory ();
}
return target;
}
static T GetDefaultCtorValue<T> ()
{
try {
return Activator.CreateInstance<T> ();
} catch {
throw new MissingMemberException ("The type being lazily initialized does not have a "
+ "public, parameterless constructor.");
}
}
}
}
#endif

Some files were not shown because too many files have changed in this diff Show More