【发布时间】:2016-06-21 04:41:07
【问题描述】:
从MS had said that both APM and EAP are outdated 开始,TAP 是在 .NET Framework 中进行异步编程的推荐方法。然后我想将我的代码从 APM 转换为 TAP:
public class RpcHelper
{
public void DoReadViaApm(IRpc rpc, BlockingCollection<ArraySegment<byte>> bc)
{
byte[] buf = new byte[4096];
rpc.BeginRead(buf, 0, buf.Length,
ar =>
{
IRpc state = (IRpc) ar.AsyncState;
try
{
int nb = state.EndRead(ar);
if (nb > 0)
{
bc.Add(new ArraySegment<byte>(buf, 0, nb));
}
}
catch (Exception ignored)
{
}
finally
{
DoReadViaApm(state, bc);
}
},
rpc);
}
public void DoReadViaTap(IRpc rpc, BlockingCollection<ArraySegment<byte>> bc)
{
Task.Factory.StartNew(() =>
{
while (true)
{
Task<byte[]> task = rpc.ReadAsync();
try
{
task.Wait(-1);
if (task.Result != null && task.Result.Length > 0)
{
bc.Add(new ArraySegment<byte>(task.Result));
}
}
catch (Exception ignored)
{
}
}
}, TaskCreationOptions.LongRunning);
}
}
public interface IRpc
{
IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state);
int EndRead(IAsyncResult asyncResult);
Task<byte[]> ReadAsync();
}
TAP方法DoReadViaTap()使用TaskCreationOptions.LongRunning,看起来很丑。我可以让 DoReadViaTap() 看起来更像 DoReadViaApm() 吗?
【问题讨论】:
标签: c# asynchronous task-parallel-library