vs-threading
vs-threading copied to clipboard
VSTHRD002 mis-fire in continuations with lambda
Bug description
![image](https://user-images.githubusercontent.com/25716486/206110959-91103296-a367-4b4b-92f3-3a16613768f9.png)
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.
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:
- Capture
t.Result
is a local variable directly within theContinueWith
delegate, and then use that within theInvokeAsync
delegate. - Optimize this by passing in a
TaskScheduler
to yourContinueWith
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.