vs-threading icon indicating copy to clipboard operation
vs-threading copied to clipboard

VSTHRD002 mis-fire in continuations with lambda

Open laolarou726 opened this issue 1 year ago • 1 comments

Bug description

image

Repro steps


var tt = Task.Run(() =>
        {
            Task.Delay(1000).Wait();
            return new int[]{1, 2};
        }).ContinueWith(t =>
        {
            Dispatcher.UIThread.InvokeAsync(() =>
            {
                Console.WriteLine(t.Result[0]);
            });
        });

In this case, t.Result[0] will trigger the warning.

laolarou726 avatar Dec 07 '22 07:12 laolarou726

Thanks for the report. I'm not sure when or if we'll get to resolving this particular issue though, as there is no end to corner cases for this.

But here are two ideas for you to avoid the warning yourself:

  1. Capture t.Result is a local variable directly within the ContinueWith delegate, and then use that within the InvokeAsync delegate.
  2. Optimize this by passing in a TaskScheduler to your ContinueWith method that executes your code on the UI thread to begin with so you don't have to continue on a threadpool thread, only to schedule more work on the UI thread.

AArnott avatar Dec 07 '22 13:12 AArnott