The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  75 Posts :: 0 Stories :: 49 Comments :: 2 Trackbacks

Ads

Archives

Post Categories

Open Source Projects

Other Blogs

I’ve been making use of Roger Alsing’s Async Fork for a few months as an alternative to the “for testing purposes only” Microsoft Parallel Extensions. With the release of C# 4.0 on the horizon, I decided to modify the internal workings of the Fork class to make use of the parallel extensions, which would result in very few modifications to my existing code. My reason for the modifications are to take advantage of the inner working of parallels extensions.

Here is the modified version of the Fork class:

 Expand Code
    public class Fork
    {
        private readonly IList<Action> _Actions ;
        private Fork()
        {
            _Actions = new List<Action>();
        }
 
        /// <summary>
        /// Starts an async fork
        /// </summary>
        /// <returns>Returns a new fork instance</returns>
        public static Fork Begin()
        {
            return new Fork();
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="action">Delegate that should be executed async</param>
        /// <returns>Returns self</returns>
        public Fork Call(Action action)
        {
            _Actions.Add(action);
            return this;
        }
 
        /// <summary>
        /// Executes all the calls async and waits untill all of them are finished
        /// </summary>
        public void End()
        {
            var taskManager = new TaskManager();
            Parallel.Invoke(_Actions.ToArray(), taskManager, TaskCreationOptions.Detached);
        }
    }

And making use of the exact same example in the original article, you can use it like this:

 Expand Code
            //declare the variables we want to assign
            string str = null;
            int val = 0;
 
            //start a new async fork
            //assign the variables inside the fork 
 
            Fork.Begin()
                .Call(() => str = CallSomeWebService(123, "abc"))
                .Call(() => val = ExecSomeStoredProc("hello"))
                .End();
 
            //the fork has finished 
 
            //we can use the variables now
            Console.WriteLine("{0} {1}", str, val);
posted on Friday, April 24, 2009 9:15 AM
Comments have been closed on this topic.