这两个异步代码块之间有什么区别?

时间:2017-08-07 11:15:00

标签: c# asynchronous

Task<int> task = new Task<int>(CountCharactersIntheFile);
task.Start();
int count=await task;

int count = await Task.Run(() => CountCharactersInTheFile());

当我根据可读性和速度编写异步代码时,我应该使用哪一个?

2 个答案:

答案 0 :(得分:2)

让我们检查来源。 Task.Run基本上用一堆默认参数调用Task.InternalStartNew。这是how that method有效:

internal static Task InternalStartNew(
    Task creatingTask, Delegate action, object state, CancellationToken cancellationToken, TaskScheduler scheduler,
    TaskCreationOptions options, InternalTaskOptions internalOptions, ref StackCrawlMark stackMark)
{
    // Validate arguments.
    if (scheduler == null)
    {
        throw new ArgumentNullException("scheduler");
    }
    Contract.EndContractBlock();

    // Create and schedule the task. This throws an InvalidOperationException if already shut down.
    // Here we add the InternalTaskOptions.QueuedByRuntime to the internalOptions, so that TaskConstructorCore can skip the cancellation token registration
    Task t = new Task(action, state, creatingTask, cancellationToken, options, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler);
    t.PossiblyCaptureContext(ref stackMark);

    t.ScheduleAndStart(false);
    return t;
}

正如您所看到的,它创建了任务,然后最终启动它。然而,它更像是正确安排它,并确保上下文。因此,只要您能够避免必须手动执行所有操作,就可以使用Task.Run。但基本上他们做的是“相同”的事情,只是在不同的深度。

答案 1 :(得分:0)

Task<int> task = new Task<int>(CountCharactersIntheFile);
task.Start();
int count=await task;

int count = await Task.Run(() => CountCharactersInTheFile());

是一样的。我的理解没有这样的差异。只需要对第一个进行缩小/ lambda格式化

相关问题