download AysncCallWrapper.cs
Language: C#
LOC: 76
Project Info
ncindy - NCindy is a .NET port of the Cind...work.(ncindy)
Server: Google
Type: svn
...indy\trunk\src\NCindy\Util\
   AbstractDisposable.cs
   AysncCallWrapper.cs
   Configuration.cs
   ElapsedTime.cs
   LangHelper.cs
   LockHelper.cs
   SocketFactory.cs
   ValueTypeWrapper.cs
   WinSock2Wrapper.cs

using System;
using System.Threading;


namespace NCindy.Util
{
    public class AysncCallWrapper<T> : IDisposable
    {
        public delegate T AysncCallFunction<T>();

        // Fields
        private AysncCallFunction<T> function;
        private Exception exception;
        private T value;
        private ManualResetEvent doneEvent;
        private bool isDone;

        // Constructors
        public AysncCallWrapper(AysncCallFunction<T> functionToRun)
        {
            this.function = functionToRun;
            ThreadPool.QueueUserWorkItem(Worker);
        }

        // Properties
        public bool IsDone
        {
            get { return isDone; }
        }

        public T Value
        {
            get
            {
                // If the future isn't completed, we wait.
                if (!isDone)
                {
                    doneEvent = new ManualResetEvent(false);
                    Thread.MemoryBarrier();
                    if (isDone)
                    {
                        doneEvent.Close();
                        doneEvent = null;
                    }
                    else
                    {
                        doneEvent.WaitOne();
                    }
                }

                // If an exception was thrown by the future, repropagate it.
                if (exception != null)
                {
                    throw exception;
                }

                return value;
            }
        }

        // Methods
        public void Dispose()
        {
            if (doneEvent != null)
            {
                doneEvent.Close();
                doneEvent = null;
            }
        }

        private void Worker(object obj)
        {
            try
            {
                value = function();
            }
            catch (Exception e)
            {
                // Capture the exception. It will be propagated when the consumer
                // rendezvous with the future.
                exception = e;
            }
            finally
            {
                isDone = true;
                Thread.MemoryBarrier();
                if (doneEvent != null)
                {
                    doneEvent.Set();
                }
            }
        }

    }
}

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us