【问题标题】:Task variable ContinueWith, await later?任务变量ContinueWith,稍后等待?
【发布时间】:2014-06-28 04:39:24
【问题描述】:

考虑以下 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 taskContinueWithawait,以下更改后的代码是否仍然正确?

        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 语句中收到编译警告。

【问题讨论】:

  • 你得到什么警告?
  • @NedStoyanov "因为没有等待这个调用,所以在调用完成之前继续执行当前方法。考虑将'await'运算符应用于调用结果。"

标签: c# asynchronous async-await


【解决方案1】:

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

 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

【讨论】:

  • 现在查看您的代码时,这一点非常明显。 :) 谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-03-15
  • 2016-03-06
  • 1970-01-01
  • 2019-10-08
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 2013-07-09
相关资源
最近更新 更多