
我最近添加了一个新功能,并在访问某些控件时开始遇到奇怪的行为.问题是某些UI控件访问只是暂停执行(没有看到异常).
仔细检查(使用WinDbg)我意识到控件是从ThreadPool线程更新的,并且抛出了CrossthreadMessagingException.
我的问题是 – 有关如何规避这种行为的良好做法吗?
这将是非常麻烦的,但也许不可能围绕使用Control.Invoke方法访问UI控件的每个代码位置.
我如何将我的代码划分为不应该使用Invoke的“安全”代码?
解决方法 如果应用程序被设计为多线程,则可能发生跨线程,因此您需要使用Invokerequired检查它,并且要么在UI线程上调用re-Invoke()本身的方法,要么抛出异常,将表明代码使用不当.请记住,Invokerequired在某些情况下将是假的(主要是当窗口没有句柄或正在处理时);防止这些情况的最好方法是不在窗口初始化过程中比Load()事件处理程序更早地启动线程,并通过取消窗口创建的后台线程并等待它们关闭来处理Closing()事件.如果应用程序不是多线程的(您没有设置BackgrounDWorkers,TPL *** 作,BeginInvoke()代理或Start()线程),那么就没有必要了.但是,对Invokerequired的调用非常便宜(其背后的逻辑基本上是检查WinAPI函数GetThreadID和GetwindowThreadProcessID返回相同的值),因此如果您预期重构的程序是多线程的,则调用方法的以下模式很简单足以实现:
//no return value,no parameters; ShowWindow(),HIDeWindow(),etc//Understand that many built-in control methods are not virtual and so you can't //overrIDe them to do this; you must either hIDe them or ensure the caller is//checking for cross-threading.public voID MyWindowMethod(){ if(Invokerequired) this.Invoke(new Action(MyWindowMethod)); else { //main logic }}//input but no return; SetTitle("My Title")public voID MyWindowMethod2(string input){ if(Invokerequired) this.Invoke(new Action<string>(MyWindowMethod2),input); else { //main logic }}//inputs and outputs; custom methods,advanced graphicspublic string MyWindowMethod3(string input){ if(Invokerequired) return (string)(this.Invoke(new Func<string,string>(MyWindowMethod3),input)); //No else required; the return makes it redundant //main logic } 总结 以上是内存溢出为你收集整理的c# – 访问UI控件时应始终使用Control.InvokeRequired全部内容,希望文章能够帮你解决c# – 访问UI控件时应始终使用Control.InvokeRequired所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)