Task variable ContinueWith, await later?

Total Post:341

Points:2389
C# 
C#
 1605  View(s)
Ratings:
Rate this:
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;
    }

I'm using part of the code in an async method. I wonder if the following altered code is still correct with regards to the var task, ContinueWith and 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)
        {

I get compilation warnings at the ContinueWith statements.

  1. Post:412

    Points:2888
    Re: Task variable ContinueWith, await later?

    Hi Ankit, 


    try this:
    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");
     }

      Modified On Apr-04-2018 05:56:27 AM

Answer