Home > Enterprise >  C# Run Task.RunSynchronously() on a different thread to where it was called
C# Run Task.RunSynchronously() on a different thread to where it was called

Time:11-30

I am working on a C# based automation desktop app (using WPF) and I have encountered an issue.

The automation process is quite computationally intensive, and as such the WPF window is completely frozen by this.

And yes, I have looked at running the code asynchronously, but that causes more errors, as code is being run before it should be.

What I need is a way to run that code on a different thread to the UI, allowing the user to interact with it while the app is running.

Thanks

CodePudding user response:

Well, the answer depends on whether you need to push results back to UI thread or not.

If not - use TPL, Parallel.For/ForEach to process collections in parallel. Methods returns ParallelLoopResult, which allows to check state of computation. See docs

Other way, as mentioned in comments, is to use Task - Task.WhenAll/Task.WaitAll. While WaitAll is essentially synchronous and still will freeze your app, WhenAll is not. I guess problems you get are related to accessing UI from non-main thread, which requires using Dispatcher (there is a method to queue Action to be ran on main thread). General advice - first await Task.WhenAll(...), then work with UI.

Also, see this article for more clues.

CodePudding user response:

As it would turn out, I was accessing the UI from the second thread, which according to WPF is a big nono.

  • Related