Geeks With Blogs
Saqib Ullah BootStrapper Know How

After a very long time I am writing this blog about one of the vital topic of the programming industry yes I am talking about Asynchronous programming. Today I gone a show you how to write a pure Async call in C#.

 

I saw lot of geeks are talking about how the actual asynchronous perform, how automatically callback calls oop it looks a rocket science but if you ask me or senior developers it not. Asynchronous call is simple as simple synchronous function calls.

By default System.Delegate provide us BeginInvoke and EndInvoke function that does actually the same operation for us. Today I am not writing this blog to show you guy how to write and use a delegate I am instead going to talk about how things work. For complete understanding Async operation we need some interfaces and classes that we required for our custom Async File Stream operation.

 

Interfaces

  • IAsyncHandler
  • IAsyncAction (not as such mandatory)

 

Classess

  • AsyncFileRead (Main class that read file and return stream)
  • AsyncFileStream (Implement IAsyncHandler)
  • AsyncOperation (Operate on AsyncFileRead class)

 

 

namespace AsyncApp

{

    public interface IAsyncHandler

    {

        IAsyncResult BeginRequest(AsyncCallback cb,object data);

        void EndRequest(IAsyncResult result);

    }

}

 

Defines methods that must be implemented for custom Async Operation in our case AsyncFileStream is the class that implement IAsyncHandler interface. AsyncFileStream class override BeginRequest and EndRequest function.

 

namespace AsyncApp

{

    public class AsyncFileStream : IAsyncHandler

    {

        private long _count = 1;

        Thread thread;

        #region IAsyncHandler Members

 

        public IAsyncResult BeginRequest(AsyncCallback cb, object data)

        {

            AsyncFileRead fileRead = new AsyncFileRead(cb, data);

            AsyncOperation operation = new AsyncOperation(fileRead);

            ThreadStart threadAction = new ThreadStart(operation.Process);

            thread = new Thread(threadAction);

            thread.Name = "Async_File" + _count.ToString();

            thread.Start();

            _count++;

            return fileRead;

        }

 

        public void EndRequest(IAsyncResult result)

        {

            AsyncFileRead read = result as AsyncFileRead;

 

            if (read.Stream != null)

                read.Stream.Close();

        }

 

        #endregion

    }

}

 

 

In BeginRequest function we take two parameters first is AsyncCallback and second is object. Here we create AsyncFileRead object by passing two args. We instantiate AsyncOperation class by passing it AsyncFileRead object and start new Thread from [operation.Process]AsyncOperation object. File open operation has been perform in this Thread.

 

EndRequest function take IAsyncResult as a parameter. In this function I casting result param into AsyncFileRead [in this case AsyncFileRead is my target class] and close the open stream.

 

namespace AsyncApp

{

    public class AsyncFileRead : IAsyncResult, IAsyncAction

    {

        private AsyncCallback m_callBack;

        private object m_data;

        private bool m_isComplete = false;

        private object m_lock = new object();

        private ManualResetEvent m_complete = null;

        private System.IO.Stream m_stream = null;

 

        public System.IO.Stream Stream

        {

            get { return m_stream; }

            set { m_stream = value; }

        }

 

        public AsyncFileRead(AsyncCallback callBack, object data)

        {

            m_callBack = callBack;

            m_data = data;

        }

 

        #region IAsyncResult Members

 

        public object AsyncState

        {

            get

            {

                return m_data;

            }

        }

 

        public System.Threading.WaitHandle AsyncWaitHandle

        {

            get

            {

                lock (m_lock)

                {

                    if (m_complete == null)

                        m_complete = new ManualResetEvent(false);

 

                    return m_complete;

                }

            }

        }

 

        public bool CompletedSynchronously

        {

            get { return false; }

        }

 

        public bool IsCompleted

        {

            get { return m_isComplete; }

        }

 

        #endregion

 

        public void Complete()

        {

            lock (m_lock)

            {

                if (m_complete != null)

                    m_complete.Set();

            }

            m_isComplete = true;

            if (m_callBack != null)

                m_callBack(this);

        }

 

        #region IMyOperation Members

 

        public System.IO.Stream Run(string filePath)

        {           

            Uri uri = new Uri(filePath);

            System.IO.FileStream fstream = null;

            if(System.IO.File.Exists(uri.AbsolutePath))

                fstream = File.OpenRead(uri.AbsolutePath);

            else

                throw new FileNotFoundException(uri.AbsolutePath);

 

            return (Stream)fstream;

        }

 

        #endregion

    }

}

 

AsyncFileRead class inherit from IAsyncResult and IAsyncAction interfaces. This class provide core implementation of Asynchronous operation. I am not going in detail of how to implement IAsyncResult interface reither then show the detail of IAsyncAction implementation.

 

namespace AsyncApp

{

    public interface IAsyncAction

    {

        System.IO.Stream Run(string filePath);

    }

}

 

Run function take file name as a parameter and open that file if exist other wise FileNotFoundException  has throw and if file exist return stream object of the file.

 

namespace AsyncApp

{

    internal class AsyncOperation

    {

        private AsyncFileRead m_AsyncResult;

 

        public AsyncFileRead AsyncResult

        {

            get { return m_AsyncResult; }

        }

 

        public AsyncOperation(AsyncFileRead obj)

        {

            m_AsyncResult = obj;

        }

 

        public void Process()

        {

            try

            {

                string _fileName = m_AsyncResult.AsyncState as string;

 

                m_AsyncResult.Stream = m_AsyncResult.Run(_fileName);

            }

            finally

            {

                m_AsyncResult.Complete();

            }

 

        }

    }

}

 

Process function of AsyncOperation class actually call the Run(string filePath) function of AsyncFileRead class in a thread.

Main Calling class code of AsyncFileStream

static void Main()

{

  AsyncCaller cal = new AsyncCaller();

  while (true) { }

}

 

class AsyncCaller

{

    IAsyncHandler read;

    public AsyncCaller()

    {

        read = new AsyncFileStream();

        read.BeginRequest(End, @"F:\CentOS_5.2-f001.vmdk");

    }

 

    void End(IAsyncResult result)

    {

        AsyncFileRead res = result as AsyncFileRead;

        Console.WriteLine("File Name {0}, File Length {1}", res.AsyncState.ToString(), res.Stream.Length);

        read.EndRequest(result);

    }

}

 

There is a lot of room available for the improvement in this example I am looking for yours feedback.

 

Posted on Saturday, August 1, 2009 4:32 AM .Net | Back to top


Comments on this post: Custom Async File Stream

# re: Custom Async File Stream
Requesting Gravatar...
Nice article..Thanks for sharing...
Left by Pankaj on Dec 22, 2009 6:54 PM

# re: Custom Async File Stream
Requesting Gravatar...
A smart move could be to specify in general on the type of clothing and to let every individual attending the wedding party to choose their own clothing; this would in turn aid in cutting charges. This can make the other person far more conscious with the price spent on gowns.

Left by cocktail mini dresses on Dec 18, 2011 6:37 PM

Your comment:
 (will show your gravatar)


Copyright © Saqib Ullah | Powered by: GeeksWithBlogs.net