Home > DeveloperSection > Forums > Task variable ContinueWith, await later?
Ankit Singh

Total Post:341

Points:2389
Posted on    August-19-2014 3:05 AM

 C# C# 
Ratings:


 1 Reply(s)
 917  View(s)
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.



Pravesh Singh

Total Post:411

Points:2881
Posted on    August-19-2014 3:29 AM

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

 }



Don't want to miss updates? Please click the below button!

Follow MindStick