Thursday 2 June 2022

c# wpf keep ui response not working (c# thread )

https://docs.microsoft.com/en-us/windows/uwp/debug-test-perf/keep-the-ui-thread-responsive


Above url says that don't put UI things with main working function.

// Perform background work here. // Don't directly access UI elements from this method.

The key point is let sub function be called inside:

await Task.Run(() => 'your function working long');




If you mix up main thread and ui thread, below error happens.
the calling thread cannot access this object




UI part code should be seprated from 'async work thread'. Otherwise you have error.



Read related article thoroughly:

https://stackoverflow.com/questions/9732709/the-calling-thread-cannot-access-this-object-because-a-different-thread-owns-it



Below code will not work for showing spinner
            uiBefore();
            ConnectionChanged();
            uiAfter();

Below code works
            uiBefore();
            await Task.Run(() =>
            {
                ConnectionChanged();
            });
            uiAfter();


        private void uiBefore()
        {
            faSpinner.Visibility = Visibility.Visible;
        }

        private void uiAfter()
        {
            faSpinner.Visibility = Visibility.Collapsed;
        }

It seems funciton inside await Task.Run() doesn't have to be async function. Only the parent function needs to be async. Below code works.


No comments:

Post a Comment