任务变量ContinueWith,等待以后?

时间:2014-05-10 13:22:20

标签: c# asynchronous async-await

请考虑以下Google示例代码:

    private Task<IUploadProgress> UploadFileAsync(DriveService service)
    {
        var title = UploadFileName;
        if (title.LastIndexOf('\\') != -1)
        {
            title = title.Substring(title.LastIndexOf('\\') + 1);
        }

        var uploadStream = new System.IO.FileStream(UploadFileName, System.IO.FileMode.Open,
            System.IO.FileAccess.Read);

        var insert = service.Files.Insert(new File { Title = title }, uploadStream, ContentType);

        insert.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * 2;
        insert.ProgressChanged += Upload_ProgressChanged;
        insert.ResponseReceived += Upload_ResponseReceived;

        var task = insert.UploadAsync();

        task.ContinueWith(t =>
        {
            // NotOnRanToCompletion - this code will be called if the upload fails
            Console.WriteLine("Upload Filed. " + t.Exception);
        }, TaskContinuationOptions.NotOnRanToCompletion);
        task.ContinueWith(t =>
        {
            Logger.Debug("Closing the stream");
            uploadStream.Dispose();
            Logger.Debug("The stream was closed");
        });

        return task;
    }

我在 async 方法中使用了部分代码。 我想知道以下更改的代码是否仍然正确 var任务 ContinueWith 等待。?

        var task = insert.UploadAsync();

        task.ContinueWith(t =>
        {
            // NotOnRanToCompletion - this code will be called if the upload fails
            Console.WriteLine("Upload Filed. " + t.Exception);
        }, TaskContinuationOptions.NotOnRanToCompletion);
        task.ContinueWith(t =>
        {
            Logger.Debug("Closing the stream");
            uploadStream.Dispose();
            Logger.Debug("The stream was closed");
        });

        await task;

        if (task.Result.Status == UploadStatus.Failed)
        {

我在ContinueWith语句中收到编译警告。

1 个答案:

答案 0 :(得分:4)

当您使用ContinueWith时,您不需要使用await,方法的其余部分会自动注册为延续。你应该能够做到:

 try
 { 
    var result = await insert.UploadAsync();
 }
 catch(Exception ex)
 {
    Console.WriteLine("Upload Filed. " + ex.Message);
 }
 finally
 {
     Logger.Debug("Closing the stream");
     uploadStream.Dispose();
     Logger.Debug("The stream was closed");
 }

link更多地解释了async\await