Skip to main content
 首页 » 编程设计

c#之任务变量 ContinueWith,稍后等待

2024年02月13日20zhwl

考虑以下 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 task、ContinueWith 和 await 而言,以下更改后的代码是否仍然正确?

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

请您参考如下方法:

当您使用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