Pergunta

Consider the following Google sample code:

    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.

Foi útil?

Solução

You don't need to use ContinueWith when you are using await, the rest of the method gets automatically registered as a continuation. You should be able to just do:

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

This link explains a bit more about async\await

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top