項目說明:
Async Activity
Async的意思是異步,但有一點一定要注意,不能按字面理解,該Activity的功能是以同步的方式調用異步方法的Activity
建議看過[WF4.0 基礎篇 (十三) InvokeMethod 調用方法 ]後,再看本文
類名 System.Activities.AsyncCodeActivity 文件 System.Activities.dll 結構說明 繼承 Activity
例1:AsyncCodeActivity
等待[BeginXXX]方法(以FileStream.BeginWrite為例)
myAsyncWriteFile
public sealed class myAsyncWriteFile: AsyncCodeActivity
{
public InArgument<string> fileName
{
set;
get;
}
public InArgument<string> fileDate
{
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> fileDate
{
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());
結果
本文示例代碼:http://www.bianceng.net/dotnet/201208/240.htm