1 //------------------------------------------------------------------------------
2 // <copyright file="AsyncOperation.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 //------------------------------------------------------------------------------
7 namespace System.ComponentModel
9 using System.Security.Permissions;
10 using System.Threading;
12 [HostProtection(SharedState = true)]
13 public sealed class AsyncOperation
15 private SynchronizationContext syncContext;
16 private object userSuppliedState;
17 private bool alreadyCompleted;
20 /// Constructor. Protected to avoid unwitting usage - AsyncOperation objects
21 /// are typically created by AsyncOperationManager calling CreateOperation.
23 private AsyncOperation(object userSuppliedState, SynchronizationContext syncContext)
25 this.userSuppliedState = userSuppliedState;
26 this.syncContext = syncContext;
27 this.alreadyCompleted = false;
28 this.syncContext.OperationStarted();
32 /// Destructor. Guarantees that [....] context will always get notified of completion.
36 if (!alreadyCompleted && syncContext != null)
38 syncContext.OperationCompleted();
42 public object UserSuppliedState
44 get { return userSuppliedState; }
47 /// <include file='doc\AsyncOperation.uex' path='docs/doc[@for="AsyncOperation.SynchronizationContext"]/*' />
48 public SynchronizationContext SynchronizationContext
56 public void Post(SendOrPostCallback d, object arg)
59 VerifyDelegateNotNull(d);
60 syncContext.Post(d, arg);
63 public void PostOperationCompleted(SendOrPostCallback d, object arg)
66 OperationCompletedCore();
69 public void OperationCompleted()
72 OperationCompletedCore();
75 private void OperationCompletedCore()
79 syncContext.OperationCompleted();
83 alreadyCompleted = true;
84 GC.SuppressFinalize(this);
88 private void VerifyNotCompleted()
92 throw new InvalidOperationException(SR.GetString(SR.Async_OperationAlreadyCompleted));
96 private void VerifyDelegateNotNull(SendOrPostCallback d)
100 throw new ArgumentNullException(SR.GetString(SR.Async_NullDelegate), "d");
105 /// Only for use by AsyncOperationManager to create new AsyncOperation objects
107 internal static AsyncOperation CreateOperation(object userSuppliedState, SynchronizationContext syncContext)
109 AsyncOperation newOp = new AsyncOperation(userSuppliedState, syncContext);