2017-08-07 81 views
-1
Task<int> task = new Task<int>(CountCharactersIntheFile); 
task.Start(); 
int count=await task; 

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

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

,当我写异步代码为每可读性和速度应该怎么用?

+3

根据我的所知,没有一个。 –

回答

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可能是一个非常好的主意,可以避免必须手动完成所有这些操作。但基本上他们只是在不同的深度做“相同”的事情。

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

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

相同。根据我的理解,没有这样的区别。只是一个缩小/ lambda格式的第一个