博客园  :: 首页  :: 联系 :: 订阅 订阅  :: 管理

WF4 Beta2:异步活动

Posted on 2009-11-12 20:55  生鱼片  阅读(487)  评论(1编辑  收藏  举报

WF4 Beta2增加了AsyncCodeActivity,在编写自定义活动时,可以实现Begin/End的异步执行方式。当异步操作执行时,不影响工作流中的其他活动,
但是工作流不会被持久化。

下面是例子:

namespace CaryAsync

{

    public sealed class FileWriter : AsyncCodeActivity

    {

        public FileWriter()

            : base()

        {

        }

 

        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)

        {           

            string tempFileName = Path.GetTempFileName();

            Console.WriteLine("Writing to file: " + tempFileName);

            FileStream file = File.Open(tempFileName, FileMode.Create);

            context.UserState = file;

            byte[] bytes = UnicodeEncoding.Unicode.GetBytes("123456789");           

            return file.BeginWrite(bytes, 0, bytes.Length, callback, state);

        }

 

        protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)

        {           

            FileStream file = (FileStream)context.UserState;        

            try

            {

                file.EndWrite(result);

                file.Flush();               

            }

            finally

            {

                file.Close();               

            }

        }

    }

}