Will using await on Task.Run casue "access to disposed closure" error?

Viewed 203

Code Sample

public async Task HeavyTask()
{
  using(var res = new BigResource())
  {
    await Task.Run(() => service.Do(res));
  }
}

I have some code that looks like above, and ReSharper warns me about "Access to disposed closure" on the use of the res instance.

If I did not use the await keyword, I know the res instance might be disposed when the service tries to access it.

But I think if I use the await keyword, the thread that executes the HeavyTask method will not continue until the Task.Run is completed, and there should be no risk of accessing a disposed closure.

Please help me understand where I went wrong, and what would be the preferred pattern to solve this problem.

1 Answers

You're not going wrong. This won't access res after it's disposed. The problem is simply that ReSharper doesn't know that. Task.Run could store the delegate in order to execute it later. The only way you know it doesn't do that is because you know what Task.Run does. ReSharper does not.

Related