简体   繁体   中英

Async within using in C# 6.0

I'm developing an application on 'VisualStudio 2017', 'C# 6.0', 'R#'. In C# 6.0 was introduced new feature - support async/await' within try/cath'. i use using operator (which is really try/finaly under the hood), but i still receive warning Access to disposed closure . But really msGet shouldn't not be disposed before DownloadToStreamAsync .

  • Does it can really access disposed variable?
  • Is it R# glitch?

my code:

using( var msGet = new MemoryStream() )
{
    var stopwatchAp = Stopwatch.StartNew();
    var stopwatchPureDownload = new Stopwatch();
    var times = new long[ 201 ];
    var retryCount = -1;
    await this._ap.Do( () =>
    {
        stopwatchPureDownload.Restart();
        var downloadToStreamAsync = blob.DownloadToStreamAsync( msGet );
        downloadToStreamAsync.ContinueWith( t => times[ ++retryCount ] = stopwatchPureDownload.ElapsedMilliseconds );
        return downloadToStreamAsync;
    } ).ConfigureAwait( false );
}

Update 1 I have seen similar questions before:

Access to disposed closure in C#? (but example here doesn't contains await , it is not about 'async/await')

Calling asynchronous method in using statement . (the answer says - use await . But as you can see my code contains await - but i still have the warning )

Also these questions dated to 2013 year. There was no C# 6.0 in 2013 year. That's why I'm asking.

Your Do method takes a Func<Task> , inside the invocation where you provide this, you include reference to msGet , this is a closure, and the compiler will turn this into a field that is accessed from your Func<Task> .

Resharper cannot be sure that your usage of the Func<Task> is within the scope or the lifetime of the using block, you could for example inside the Do method, copy the func into a field and call it again later.

If you are executing the Func<Task> immediately inside of Do you can safely ignore the warning with:

// ReSharper disable once AccessToDisposedClosure

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM