Simplified automatic processing InvokeRequired code mode
The traditional InvokeRequired code mode is complicated and frustrating in the GUI event processing. This mode needs to check whether the current thread can access the handle of the control. If not, call and change it on the correct thread.
In order to solve this problem, we improved the method of Lee and developed a simplified method:
This method has expanded the Control class. The method of use is as follows:
<code class="language-csharp">public static void InvokeIfRequired(this Control control, MethodInvoker action) { // 检查可见性,如有必要则调用 while (!control.Visible) { System.Threading.Thread.Sleep(50); } if (control.InvokeRequired) { control.Invoke(action); } else { action(); } }</code>
For the situation that needs to be returned, you can use this replacement implementation:
<code class="language-csharp">richEditControl1.InvokeIfRequired(() => { // 操作控件 richEditControl1.RtfText = value; RtfHelpers.AddMissingStyles(richEditControl1); });</code>
In addition to Control, the Isynchronizeinvoke interface can also benefit from this method:
<code class="language-csharp">private static T InvokeIfRequiredReturn<T>(this Control control, Func<T> function) { if (control.InvokeRequired) { return (T)control.Invoke(function); } else { return function(); } }</code>
It is worth noting that Isynchronizeinvoke needs an object array as a parameter list of the INVOKE method. However, if there are no parameters, you can pass NULL, as described in the document.
<code class="language-csharp">public static void InvokeIfRequired(this ISynchronizeInvoke obj, MethodInvoker action) { if (obj.InvokeRequired) { obj.Invoke(action, null); } else { action(); } }</code>
We admit that when the control is initially visible, it may sometimes encounter a false alarm. To solve this problem, we added a 50 millisecond sleep interval in visible examination. Although this method is usually valid, its effectiveness may depend on the specific use cases and time requirements in your application.
The above is the detailed content of How Can I Simplify InvokeRequired Code in GUI Event Handling?. For more information, please follow other related articles on the PHP Chinese website!