项目说明: Async Activity Async的意思是异步,但有一点一定要注意,不能按字面理解,该Activity的功能是以同步的方式调用异步方法的Activity 建议看过[WF4.0 基础篇 (十三) InvokeMethod 调用方法 ]后,再看本文 类名 | System.Activities.AsyncCodeActivity | 文件 | System.Activities.dll | 结构说明 | 继承 Activity 是一个 abstract类 override 了 [CacheMetadata方法] 提供两个 abstract方法 [BeginExecute],[EndExecute] | 功能说明 | AsyncCodeActivity的主要目的是实现当Activity中有异步操作时,如何等待有异步完成后才向下执行的问题,也就是说如何将并行变为串行 |
类名 | System.Activities.AsyncCodeActivity<TResult> | 文件 | System.Activities.dll | 结构说明 | 继承 Activity<TResult> 是一个 abstract类 override 了 [CacheMetadata方法] 提供两个 abstract方法 [BeginExecute],[EndExecute] | 功能说明 | 与AsyncCodeActivity,可以在[EndExecute]方法中return 返回值 |
例1:AsyncCodeActivity 等待[BeginXXX]方法(以FileStream.BeginWrite为例) myAsyncWriteFile | public sealed class myAsyncWriteFile: AsyncCodeActivity { public InArgument<string> fileName { set; get; } public InArgument<string> fileData { set; get; } protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state) { string fn = context.GetValue(fileName); string fd = context.GetValue(fileData); System.Console.WriteLine("开始写入文件"); FileStream fileStream = File.Open(fn, FileMode.Create); context.UserState = fileStream; byte[] bytes = UnicodeEncoding.Unicode.GetBytes(fd); IAsyncResult r = fileStream.BeginWrite(bytes, 0, bytes.Length, callback, state); return r; } protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result) { System.Threading.Thread.Sleep(5000); FileStream file = (FileStream)context.UserState; file.EndWrite(result); file.Flush(); file.Close(); System.Console.WriteLine("写入文件完成"); } } | 流程 | | 宿主 | WorkflowInvoker.Invoke(new myAsyncWriteFileWorkflow()); | 结果 | |
例2:AsyncCodeActivity<TResult> 等待[BeginXXX]方法(以FileStream.BeginWrite为例) myAsyncWriteFileByResult | public sealed class myAsyncWriteFileResult : AsyncCodeActivity<string> { public InArgument<string> fileName { set; get; } public InArgument<string> fileData { set; get; } protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state) { string fn = context.GetValue(fileName); string fd = context.GetValue(fileData); System.Console.WriteLine("开始写入文件"); FileStream fileStream = File.Open(fn, FileMode.Create); context.UserState = fileStream; byte[] bytes = UnicodeEncoding.Unicode.GetBytes(fd); IAsyncResult r = fileStream.BeginWrite(bytes, 0, bytes.Length, callback, state); return r; } protected override string EndExecute(AsyncCodeActivityContext context, IAsyncResult result) { System.Threading.Thread.Sleep(5000); FileStream file = (FileStream)context.UserState; file.EndWrite(result); file.Flush(); file.Close(); System.Console.WriteLine("写入文件完成"); return "写入成功"; } } | 流程 | | 宿主 | WorkflowInvoker.Invoke(new myAsyncWriteFileByResultWorkflow()); | 结果 | | 本文示例源代码或素材下载 (责任编辑:admin) |