相关疑难解决方法(0)

Task.Factory.FromAsync和BeginX/EndX之间的区别?

当使用TcpClient中的标准BeginRead和EndRead方法并使用Task.Factory.FromAsync时,我有非常相似的代码.

以下是一些示例..错误处理代码未显示.

Task.Factory.FromAsync:

private void Read(State state)
{
    Task<int> read = Task<int>.Factory.FromAsync(state.Stream.BeginRead, state.Stream.EndRead, state.Bytes, state.BytesRead, state.Bytes.Length - state.BytesRead, state, TaskCreationOptions.AttachedToParent);

    read.ContinueWith(FinishRead);
}

private void FinishRead(Task<int> read)
{
    State state = (State)read.AsyncState;

    state.BytesRead += read.Result;
}
Run Code Online (Sandbox Code Playgroud)

使用BeginRead和EndRead标准使用回调:

private void Read(State state)
{
    client.BeginRead(state.Bytes, state.BytesRead, state.Bytes.Length - state.Bytes.Read, FinishRead, state);
}

private void FinishRead(IAsyncResult async)
{
    State state = (State)async.AsyncState;

    state.BytesRead += state.Stream.EndRead(async);
}
Run Code Online (Sandbox Code Playgroud)

这两个都很好,但我很好奇他们的差异.两者的代码行几乎相同,它们似乎都执行完全相同的功能并具有相同的效率.哪个更好?您更喜欢在生产代码中看到什么?

.net c# asynchronous task-parallel-library

11
推荐指数
1
解决办法
2961
查看次数

标签 统计

.net ×1

asynchronous ×1

c# ×1

task-parallel-library ×1