TASK VARIABLE CONTINUEWITH, AWAIT LATER?

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
C# 
C#
 1357  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. Pravesh Singh

    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");

     }


Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!