I have a long-running task and I would like to add a cancel button and a progress bar. The problem is:
- My .NET Framework and WPF code runs inside SolidWorks, which is basically single-threaded.
- Doing long-running tasks makes the UI unresponsive. This also happens with native SolidWorks features.
- Wrapping the work in a Task.Run makes SolidWorks API calls 10-100x times slower, so that's not an option.
Is there a to make a custom dialog that updates at least once a second? Right now my button click are hardly ever registered with a standard Window.
CodePudding user response:
Try rewriting your code but instead of using Threads, that will freeze your Application, use an async function. This will not only update your progress bar but also you will have a fully interactable UI.
Also see: WPF UI Freezes - UI Thread conflict?
How to run and interact with an async Task from a WPF gui
https://mithunvp.com/building-responsive-ui-using-async-await-csharp/
(Async functions run in background wich is great for stuff like downloading files with progress bar and cancle button or your long time task)
CodePudding user response:
It is not possible to have a responsive UI when you are running resource intensive code in the UI thread.
Since Task.Run makes api calls slower you could try to create a new thread instead like this:
using System.Threading;
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
// Your code here
}).Start();
I am not sure if it will be faster than Task.Run, but you could give it a try