Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VSTHRD002 mis-fire in continuations with lambda #1123

Open
laolarou726 opened this issue Dec 7, 2022 · 1 comment
Open

VSTHRD002 mis-fire in continuations with lambda #1123

laolarou726 opened this issue Dec 7, 2022 · 1 comment

Comments

@laolarou726
Copy link

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.

@AArnott
Copy link
Member

AArnott commented Dec 7, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants