How to execute code in the GUI Thread?

前端 未结 6 1097
我在风中等你
我在风中等你 2021-01-12 03:56

I have a FileSystemWatcher that react on the Changed event.

I want to open the file, read its content display it in a textbox and hide the popup that has been create

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 04:17

    The problem is that extendedNotifyIcon_OnHideWindow is being executed on a thread other than the UI thread. You will need to use the Dispatcher for that part as well. Also, I would not create a dedicated thread just to wait one second. You could easily refactor that part into a System.Threading.Timer. Here is my refactored version.

    txtLog.Dispatcher.Invoke(
        (Action)(() =>
            {
                txtLog.Text = dataToDisplay;
                extendedNotifyIcon_OnShowWindow(); 
                new Timer(
                    (state) =>
                    {
                        button1.Dispatcher.BeginInvoke(
                            (Action)(() =>
                                {
                                  extendedNotifyIcon_OnHideWindow(); 
                                }), null);
                    }, null, 1000, Timeout.Infinite);
            }));
    

提交回复
热议问题