无法更改 TimedEvent() 的背景颜色;

Can't change background color out of TimedEvent();

提问人:user20202784 提问时间:10/10/2022 最后编辑:Stefan Wuebbeuser20202784 更新时间:10/11/2022 访问量:49

问:

在我的 C# WPF 项目中,我有一个定时事件。在 timedEvent 中,我有多个 try catch 函数。 例如:

try
            {
                StreamWriter sw = new StreamWriter("Dateien/DB/Box" + boxnumber + "_Abwesenheit.txt", true, Encoding.ASCII);
                sw.Write("\n" + WNR_KNR[1] + datetime);
                sw.Close();
                Rec_Background.Fill = new SolidColorBrush(Color.FromRgb(255, 255, 0));
            }
            catch (Exception y)
            {
                Console.WriteLine("Exception; " + y.Message);
            }
            finally
            {
                Console.WriteLine("Abwesenheit automatisch Pause(1059)");
                absence = true;
            }

在Rec_background。填充 = new SolidColorBrush(Color.FromRgb(255, 255, 0));

我抛出了一个异常:

引发异常:WindowsBase.dll中的“System.InvalidOperationException” 线程0xf4c已退出,代码为 0 (0x0)。 例外;Der aufrufende Thread kann nicht auf dieses Objekt zugreifen, da sich das Objekt im Besitz eines anderen Threads befindet. 线程0x4848已退出,代码为 0 (0x0)。

此异常在 timed Event 中多次引发。例如,当我尝试写入文本文件时。 但这只发生在 TimedEvent 中,没有其他地方。

C# WPF 异常 时间 定时事件

评论

0赞 Stefan Wuebbe 10/10/2022
这听起来像是 ,或者您目前显示的代码之外的进程出了问题。作为一个疯狂的猜测,我建议尝试将该过程的根源放入async/awaitBackgroundWorkerDispatcherTimerasyncDispatcher.BeginInvoke()
0赞 user20202784 10/10/2022
我看到这个 Dispatcher.BeginInvoke() akready。这到底是什么或如何使用它?

答:

0赞 user20202784 10/10/2022 #1

把这个放在Rec_background面前......解决了。 Application.Current.Dispatcher.Invoke(() =>