Since MS had said that both APM and EAP are outdated, TAP is the recommended approach to asynchronous programming in the .NET Framework. Then I want to convert my code from APM to 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();
}
The TAP method DoReadViaTap() use TaskCreationOptions.LongRunning, it looks very ugly. Can I make DoReadViaTap() looks better like DoReadViaApm() ?