Is it good idea to use “Control.CheckForIllegalCrossThreadCalls = false” [duplicate]

浪尽此生 提交于 2019-11-26 21:41:20

问题


This question already has an answer here:

  • Is it safe just to set CheckForIllegalCrossThreadCalls to false to avoid cross threading errors during debugging? 1 answer

I have a class that receives data from serialport. i used action<T> delegate to pass data to the form where it is displayed in a textbox. the thing is i could not access the textbox control, becouse it says: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.

so i set Control.CheckForIllegalCrossThreadCalls = false, and it is working.

is it good idea to do that? or there is a better way of doing it.

Thanks


回答1:


While it may appear to work most of the time, it is sure to fail every now and then.

If you need to access/modify the UI control from another thread, use Control.Invoke.




回答2:


Not a good idea to do that.

I believe the preferred method is to check to see if Control.InvokeRequired == true, and if so then use Control.Invoke with the proper delegate, which will marshall the method call onto the UI thread.




回答3:


Will you write something like below

       try
        {
            Object obj=null;
            var result = obj.ToString();
        }
        catch (Exception )
        {


        }

I am sure your answer would be NO , similar thing is with Control.CheckForIllegalCrossThreadCalls = false, it will just eating exception but present unknown results to your estimated clients



来源:https://stackoverflow.com/questions/15516014/is-it-good-idea-to-use-control-checkforillegalcrossthreadcalls-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!