开发者

When should I check for InvokeRequired when calling another threads object?

In my main form, I create an object that uses file IO and retains an open handle. I then spawn a thread which creates another form, which needs to use this same object. The constructor of t开发者_StackOverflow社区he second form accepts a reference to the first forms IO object. Should I check for RequireInvoke when calling methods of this IO object in the second form even though said object is not UI control related?


If the object u r sharing between the 2 threads is not a ui control then you dont have to worry about a cross thread exception.

If you ask me the more pressing thing would be data validity when it is shared across threads. Cross thread access exceptions are pretty straight forward to locate and resolve.


So what you have is two UI threads, both of which access the object.

What you need to understand about InvokeRequired is that all it does is check if the currently executing thread is the same thread that the Control was created on.

bool InvokeRequired
{
   // vastly simplified
   get { return GetCurrentThreadId() != GetWindowThreadId(this.Handle); }
}

So why is this important? Because Windows windows (controls, et al) can only be safely sent messages from the same thread that created them. They are not inherently thread safe. Changing properties on controls usually requires messages to be sent.

So you only need to check InvokeRequired if you are about to alter a property of some control. If you are, and InvokeRequired returns true than you need to use Control.Invoke or Control.BeginInvoke to execute the property change from thread that owns the control.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜