Can I create a thread safe Winform User Control

Hi, 
   I know that if I want to update a Windows Form Control from a worker 
thread I need to check InvokeRequired on the control and jump through some 
hoops. I can get that all to work. But, I wonder if I can make a User Control 
which inherits from for example, System.Windows.Forms.Label, and has the 
correct thread safe set method built in? In fact, why are Windows Forms 
controls not thread safe? It seems like it would have been pretty easy to 
build in, at least for the their simple properties, and would save a fair 
amount of fiddly work on the developer's part.

Thanks,
Ethan
0
Utf
11/19/2009 5:36:01 PM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

4 Replies
874 Views

Similar Articles

[PageSpeed] 29

Ethan Strauss wrote:
> Hi, 
>    I know that if I want to update a Windows Form Control from a worker 
> thread I need to check InvokeRequired on the control and jump through some 
> hoops. I can get that all to work. But, I wonder if I can make a User Control 
> which inherits from for example, System.Windows.Forms.Label, and has the 
> correct thread safe set method built in?

No, you can't, not really.  At best, you could hide the existing public 
methods with a wrapper that does the necessary work, or implement a 
whole new separate API, but it would always be possible to call the 
un-wrapped methods in code that isn't aware of your specific subclass type.

> In fact, why are Windows Forms 
> controls not thread safe? It seems like it would have been pretty easy to 
> build in, at least for the their simple properties, and would save a fair 
> amount of fiddly work on the developer's part.

I've wondered the same thing, and don't have a specific answer.  But I 
suspect it's related to the fact that a) there's a certain amount of 
performance overhead that would be incurred in _all_ scenarios, 
including the 95% case of not needing multi-threading support, b) doing 
the cross-thread invocation implicitly introduces the possibility of 
deadlock to a developer who may not know much or anything about 
threading bugs, and c) making the cross-thread invocation an explicit 
implementation detail allows for the client code to determine on a 
case-by-case basis whether to use synchronous invocation (Invoke()) or 
asynchronous invocation (BeginInvoke()).

There may yet be other reasons I haven't considered.

Pete
0
Peter
11/19/2009 6:29:33 PM
Thanks Pete, 
   It still seems odd that they couldn't build it in. It could be a 
ThreadSafeSetText() type method and still leave the standard methods and 
properties in place. Oh well. It's not that hard to do my own. 
   A strange thing I just noticed is that, using vsto, the controls in the 
ribbon (Microsoft.Office.Tools.Ribbon.RibbonControl) don't have an 
InvokeRequired property. I wonder if they are already thread safe? I found 
this statement "Any public static (Shared in Visual Basic) members of this 
type are thread safe. Any instance members are not guaranteed to be thread 
safe. " about ribbon controls, but I am not sure what is meant by "public 
static members" and "instance members".  That's from 
http://msdn.microsoft.com/en-us/library/microsoft.office.tools.ribbon.ribboncontrol.aspx
Ethan


"Peter Duniho" wrote:

> Ethan Strauss wrote:
> > Hi, 
> >    I know that if I want to update a Windows Form Control from a worker 
> > thread I need to check InvokeRequired on the control and jump through some 
> > hoops. I can get that all to work. But, I wonder if I can make a User Control 
> > which inherits from for example, System.Windows.Forms.Label, and has the 
> > correct thread safe set method built in?
> 
> No, you can't, not really.  At best, you could hide the existing public 
> methods with a wrapper that does the necessary work, or implement a 
> whole new separate API, but it would always be possible to call the 
> un-wrapped methods in code that isn't aware of your specific subclass type.
> 
> > In fact, why are Windows Forms 
> > controls not thread safe? It seems like it would have been pretty easy to 
> > build in, at least for the their simple properties, and would save a fair 
> > amount of fiddly work on the developer's part.
> 
> I've wondered the same thing, and don't have a specific answer.  But I 
> suspect it's related to the fact that a) there's a certain amount of 
> performance overhead that would be incurred in _all_ scenarios, 
> including the 95% case of not needing multi-threading support, b) doing 
> the cross-thread invocation implicitly introduces the possibility of 
> deadlock to a developer who may not know much or anything about 
> threading bugs, and c) making the cross-thread invocation an explicit 
> implementation detail allows for the client code to determine on a 
> case-by-case basis whether to use synchronous invocation (Invoke()) or 
> asynchronous invocation (BeginInvoke()).
> 
> There may yet be other reasons I haven't considered.
> 
> Pete
> .
> 
0
Utf
11/20/2009 3:06:06 PM
Ethan Strauss wrote:
> [...]
>    A strange thing I just noticed is that, using vsto, the controls in the 
> ribbon (Microsoft.Office.Tools.Ribbon.RibbonControl) don't have an 
> InvokeRequired property. I wonder if they are already thread safe?

Careful.  There's a difference between the thread affinity that involves 
InvokeRequired and thread safety.  For example, even if you synchronized 
all access to your System.Windows.Forms.Control sub-classes so that an 
instance was ever only accessed on one thread at a time, you would 
_still_ have the requirement that the non-client class members (i.e. 
those not added by you in a sub-class) be accessed only on the thread 
that owns the instance.

Conversely, just because some other type of GUI control doesn't inherit 
from the System.Windows.Forms.Control class, nor have an InvokeRequired 
property, that doesn't mean that the type is thread-SAFE.  It just 
(probably) means that the control doesn't have the same thread affinity 
issue that the System.Windows.Forms.Control sub-classes do.

(I say probably because the control you're asking about is part of the 
Office interop types, which I'm not that familiar with.  I don't know 
for sure that it doesn't have a thread affinity issue).

> I found 
> this statement "Any public static (Shared in Visual Basic) members of this 
> type are thread safe. Any instance members are not guaranteed to be thread 
> safe. " about ribbon controls, but I am not sure what is meant by "public 
> static members" and "instance members".  That's from 
> http://msdn.microsoft.com/en-us/library/microsoft.office.tools.ribbon.ribboncontrol.aspx

That language is Microsoft's standard boilerplate language for .NET 
types.  Again, it doesn't relate to thread affinity, but rather to 
thread safety, which is not quite the same thing.

In particular, in that type (and others with the same comment, which is 
something like 90% or more of .NET) your code can safely access static 
members of the type without synchronization between threads.  But for a 
given instance, your own code is required to handle synchronization if 
more than one thread is accessing members _of that instance_ at the same 
time.

Note that individual instances are independent of each other.  You can 
access instance members of one instance in one thread and instance 
members of a different instance in another thread without needing to 
synchronize the two threads.

Note also that for controls that _do_ have thread affinity, the thread 
safety issue tends to be moot, because your code is always only ever 
accessing instances of controls like that on the thread that owns the 
control.  The control is, in addition to having thread affinity, also 
_not_ thread safe for instance members, but because you can't even 
access the members of the class except on the owning thread, the lack of 
thread safety isn't an issue (*).

Pete

(*) (unless, of course, you are dealing with your own sub-class and 
members that you know to not have thread affinity issues...then you do 
have to deal with the lack of thread-safety if you choose to access 
those client-declared members in multiple threads simultaneously).
0
Peter
11/20/2009 6:37:24 PM
Thanks Pete, 
That was quite helpful. I didn't even know thread affinity existed!
Ethan

"Peter Duniho" wrote:

> Ethan Strauss wrote:
> > [...]
> >    A strange thing I just noticed is that, using vsto, the controls in the 
> > ribbon (Microsoft.Office.Tools.Ribbon.RibbonControl) don't have an 
> > InvokeRequired property. I wonder if they are already thread safe?
> 
> Careful.  There's a difference between the thread affinity that involves 
> InvokeRequired and thread safety.  For example, even if you synchronized 
> all access to your System.Windows.Forms.Control sub-classes so that an 
> instance was ever only accessed on one thread at a time, you would 
> _still_ have the requirement that the non-client class members (i.e. 
> those not added by you in a sub-class) be accessed only on the thread 
> that owns the instance.
> 
> Conversely, just because some other type of GUI control doesn't inherit 
> from the System.Windows.Forms.Control class, nor have an InvokeRequired 
> property, that doesn't mean that the type is thread-SAFE.  It just 
> (probably) means that the control doesn't have the same thread affinity 
> issue that the System.Windows.Forms.Control sub-classes do.
> 
> (I say probably because the control you're asking about is part of the 
> Office interop types, which I'm not that familiar with.  I don't know 
> for sure that it doesn't have a thread affinity issue).
> 
> > I found 
> > this statement "Any public static (Shared in Visual Basic) members of this 
> > type are thread safe. Any instance members are not guaranteed to be thread 
> > safe. " about ribbon controls, but I am not sure what is meant by "public 
> > static members" and "instance members".  That's from 
> > http://msdn.microsoft.com/en-us/library/microsoft.office.tools.ribbon.ribboncontrol.aspx
> 
> That language is Microsoft's standard boilerplate language for .NET 
> types.  Again, it doesn't relate to thread affinity, but rather to 
> thread safety, which is not quite the same thing.
> 
> In particular, in that type (and others with the same comment, which is 
> something like 90% or more of .NET) your code can safely access static 
> members of the type without synchronization between threads.  But for a 
> given instance, your own code is required to handle synchronization if 
> more than one thread is accessing members _of that instance_ at the same 
> time.
> 
> Note that individual instances are independent of each other.  You can 
> access instance members of one instance in one thread and instance 
> members of a different instance in another thread without needing to 
> synchronize the two threads.
> 
> Note also that for controls that _do_ have thread affinity, the thread 
> safety issue tends to be moot, because your code is always only ever 
> accessing instances of controls like that on the thread that owns the 
> control.  The control is, in addition to having thread affinity, also 
> _not_ thread safe for instance members, but because you can't even 
> access the members of the class except on the owning thread, the lack of 
> thread safety isn't an issue (*).
> 
> Pete
> 
> (*) (unless, of course, you are dealing with your own sub-class and 
> members that you know to not have thread affinity issues...then you do 
> have to deal with the lack of thread-safety if you choose to access 
> those client-declared members in multiple threads simultaneously).
> .
> 
0
Utf
11/23/2009 4:07:01 PM
Reply:

Similar Artilces:

Getting a subform control to requery
Main Form : F_BU Subform1: F_BU_Cat2 SubForm2: F_BU_Cat3 When I click on one of the records in subform1 (field BillCat) the OnClick event uses the value in the field as a criteria in a query that is used in the combox (cbxCat3) in Subform 2. Here is the code I was trying to use: Me.Parent!F_BU_Cat3.Form!cbxCat3.Requery It was working for a while but now not when I click on the "BillCat" field in Subform 1 I get: Method: Form" of Object ' _Subform' Failed. -- Message posted via AccessMonster.com http://www.accessmonster.com/Uwe/Forums.aspx/access-form...

can't print black
I have installed a lexmark 6570 fax wireless. It would not print any doc's in black ink prints beautiful color pictures. I uninstalled and reinstalled did not help. I figured is was the printer. Installed an HP F4280 all in one, same problem. can someone get me some advice!!! -- twilltwo ------------------------------------------------------------------------ twilltwo's Profile: http://forums.techarena.in/members/180192.htm View this thread: http://forums.techarena.in/vista-help/1297957.htm http://forums.techarena.in ...

how i can change default file format Outlook uses to save message
I my saving message in my inbox using "File->Save As" menu. "Save As.." dialog by default shows "Save As Type:" as "HTML". How I can change default file format Outlook uses to save messages to as "Outlook Message Format - Unicode" ?????? Rajkumar <Rajkumar@discussions.microsoft.com> wrote: > I my saving message in my inbox using "File->Save As" menu. > "Save As.." dialog by default shows "Save As Type:" as "HTML". > How I can change default file format Outlook uses to save messages...

can I get "step by step" on color seperating for commercial printi
This is kind of an extension on my previous message but I feel it would help a lot more. Can someone give me a quick step by step on making a document with text and photo into a press quality color seperated piece using PMS colors and process black? Or maybe point me to a site that can give step by step on that stuff? ...

Forcing users to click an action button to advance the slide
I am trying to have a PPS that forces users to click an action button to continue. I want to force them to go through each slide vice just quickly hitting keys to jump to the end of the show. I am unsure of what I have to disable to allow this to happen. Hi Slide Show -> Set up show -> Browsed at kiosk will disable all ways of advancing the presentation except for 'buttons' on screen. Lucy -- Lucy Thomson PowerPoint MVP MOS Master Instructor www.aneasiertomorrow.com.au "Azlian" <Azlian@discussions.microsoft.com> wrote in message n...

Where can we get xml scheme for tuning setting of WM2003/WM5.0 PDA
Hi all, We are working upon setting up a lot of WM2003/WM5.0 empowered mobile devices according with company standards. As far as I know these settings are tuned through xml file. Then this xml file has to be deployed deployed/executed onto mobile device. My question is where xml scheme for tuning such setting is published so we may assign necessary properties referencing it? Thank you in advance. ...

Re: Can anyone help me with the IF function
Hello I'm trying to help my wife with simplifying her scheduling o employees. She uses 11 different time periods (1-11) some are worth the same amount of hours others are more or less. I can us seven functions to describe the period and the value of hours it is worth, but when I consolidate the functions i says the formula is invalid. I'm sure it can be fixed by one of you excel gurus! Here are the functions IF(B13<4,"7.75") IF(B13=4,"7.25") IF(B13=5,"6.25") IF(B13=6,"7.75") IF(B13=7,"6.75") IF(B13=8,"6.25") IF(B...

How can I connfigure my outlook to access same profile accross mu.
How can I connfigure my outlook to access same profile accross multiple user ids on a computer Krishna <Krishna@discussions.microsoft.com> wrote: > How can I connfigure my outlook to access same profile accross > multiple user ids on a computer You can't. Each user ID will have its own profile, sicne profile information is kept in the registry in a user-specific area. However, you can certainly reference the same message store within each profile. For POP accounts, just put the PST somewhere in the Shared Documents hierarchy and point to it within each profile. -- B...

Can administrator empty Deleted items in each mailbox
Hi, Is there any chance that administrator can delete all items in Deleted items folder? Tx, Gasper Are you talking in each user's mailbox or the deleted items available for restore? What version of Exchange? -- Regards, Hank Arnold "Gasper" <NOSPAMgasper.derzanic@tipro.si> wrote in message news:tAfEb.108$%x4.10122@news.siol.net... > Hi, > > Is there any chance that administrator can delete all items in Deleted items > folder? > > Tx, > > Gasper > > > > Is it possible to delete Deleted items in each user mailbox on Exchange ...

Active Directory Problem
Hi Everyone, Hopefully you can help me out a bit here. Long story short, we had a failure last week that we were unable to recover Active Directory from. As such, we've had to rebuild AD from scratch - now the domain name and all user accounts are recreated and identical to the previous setup. However, I can no longer access CRM. I assume CRM 4.0 is authenticating on, not only AD membership, but based on an AD GUID of some sort - which I can't replicate. How can I get back in to re-load my users? Thanks, Craig Hi, Did u check if the users were part of CRM groups created ...

Can't Connect to Bank with Money 04 Trial Version
Hi, Does anyone know why I can't connect to my bank through the trial version of Money 04? I use quicken at the moment and after reading the negative reviews of the 04 update have decided to give money a try. The bank appears on the list of participating institutions and indicates that it is set up for direct connect/two way communication. However, when I go through the Online Services Manager it is listed under the heading "Banks that have no Service". I would appreciate any answers! Sarah ...

IP Address control
Hi, I have two questions regarding this stupid control. I use CIPAddressCtrl to access it. 1. How do I make it read only? I can disable it, but then the text is gray, while I want it black as an ordinary edit box which is set as read only. 2. Why does it send an IPN_FIELDCHANGED even when I'm just using the arrow keys? With an address like 192.168.1.111, it sends this message when I'm on the single digit entry "1", which is quite annoying. The address isn't changed! Anyone knows of an easy workaround? thanks /Glenn I haven't done this but you could try deriving...

Cannot create new mailbox
I'm having an issue of not being able to create a new mailbox. I can go through the process of creating the user in AD Users & Computers and everything is successfull. I can even see the user in the GAL. But I cannot access the mailbox by opening it nor does it show up in system manager even after sending a message to the mailbox. I do have full permissions to the mailbox. It seems like it is not being created even though the recipient policy seems to be working because it does generate an address for the account. Any help would be appreciated. ...

Creating Excel Invoice Template
I have been trying to customize a downloaded template but was frustrated so trying to create my own invoice. My question is once I input the formulas how do I keep/save them ???? when I enter the first calcualtions all is well, but if I go back and edit in the cell where the formula resides I lose the formula ??? I am a relative newbie to this so any help will be greatly appreciated. I have searched this site and cannot find a link to creating an invoice worksheet. Sasha ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions wit...

How can I see which lists a contact is a member of?
Hello, In Outlook 2007, is there a way to see which distribution lists a contact is a member of? We have lots of lists. We want to be sure that if we delete a contact in a group, instead of just removing it from the group, that the contact doesn't exist in other groups as well. Even a way to export to Excel would be ok, if there's nothing else. Thanks, - Alan. The following macro in Outlook will list all the distribution lists containing the name you enter into the dialog box in a Word document Sub ListNames() Dim wdApp As Word.Application Dim wdDoc As Word.Document Dim myNameSp...

how do i create a macro to export a chart to powerpoint?
Can anyone give me any tips to create a macro to export data to powerpoint. When I try to record the sequence it falls over at the 'copy' stage. Hi, Have you seen Jon's page on the subject? http://peltiertech.com/Excel/XL_PPT.html Cheers Andy -- Andy Pope, Microsoft MVP - Excel http://www.andypope.info "NPAT" <NPAT@discussions.microsoft.com> wrote in message news:BE9FBC41-25D4-4A27-8CBF-CF0F8E55D838@microsoft.com... > Can anyone give me any tips to create a macro to export data to > powerpoint. > When I try to record the sequence it falls over at ...

can not delete in outlook
When I try to delete anything out of outlook i get the following errror The messaging interface have returned an unknown error. If problem presists restart outlook Sam wrote: > When I try to delete anything out of outlook i get the > following errror > > The messaging interface have returned an unknown error. > If problem presists restart outlook OL2000: Error Message: The Messaging Interface Has Returned an Unknown Error http://support.microsoft.com/?kbid=275186 -- G�rard gj.oomens@somso.demon.nl ...

can I lock screen so only clicked links move slides in sldeshow
I have created question slides with Yes and No links to the next corresponding slides eg if answer yes link goes to slide 2 if answer No goes to slide 3 this happens during slide show presentation I want to be able to lock the rest of the slide so that only a link click can progress to the next slide because the process does not run in order if you just click anywhere on the screen to progress the slides On Jan 28, 5:19=A0pm, Workworry <Workwo...@discussions.microsoft.com> wrote: > I have created =A0question slides with Yes and No links to the next > corresponding ...

Error created when try to Print Preview or Print
When try to print or print preview system is generating an error: "Print titles must be contiguous and complete rows or columns." Used excel for years ever seen this error before. Using Excel 2007 on Vista, we just upgraded to SP2 for both systems. After testing a few times, I notice that system is generating a Name Range with no referencing cell range, the name range is called Print_Titles. If I delete the name range it removes the error message and able to use print preview and able to print. Notice it is occurring more ofter when client is copying a worksheet to ...

Can I import a .pdf file into publisher
I tried to copy and paste from InDesign and it did not work. Can you import any type of file into publisher. Example: .pdf or .eps No. Publisher is pretty much a stand all by itself program. If you can't copy and paste into it, you're kind of sorely out of luck. You can put pictures into a Pub file but you can't go back and edit the individual parts of them, such as text. -- JoAnn Paules MVP Microsoft [Publisher] "Graphix grl" <Graphixgrl@discussions.microsoft.com> wrote in message news:88493145-8B59-4131-AD33-C916D22CF63C@microsoft.com... >I tried...

Blocked and safe senders file in Outlook 2003
Hi, I am wondering where outlook 2003 saves the address that you add to the safe sender/recipient and blocked sender list. Outlook XP saved the junk senders in a file called "Junk senders" in C:\Documents and Settings\my_id\Application Data\Microsoft\Outlook I used to backup that file, so I would like to know where Outlook keeps the file now. Thank you The lists are kept in binary values in the Windows registry and also in a hidden item in the mail store (mailbox or PST file). Both lists are kept in one multivalued property although no one has decoded it yet, the bits also s...

Modal dialog as thread
The following 3 step procedure was taken form CodeGuru article named Convert modal dialogs to modeless by Jon S. Kyle It works greate but I can't figure out how to modify controls text on the dialog box while its already diplayed. Can someone advise please? Rami 1. In your header file define a CWinThread-derived class... class CDialogThread : public CWinThread { DECLARE_DYNCREATE(CDialogThread) CDialogThread() {}; virtual BOOL InitInstance(); }; 2. Put this in your implementation file (where CSomeDialog is a conventional dialog class defined the usual way). IMPLEMENT_DYNCREATE(CD...

User Access Reporting
Hello Everybody, Does anyone know of a better way to audit security for individual users that the User Security report? Even with the options set to include Accessible Items only, we're finding the report for a single user runs well over 100 pages. With that kind of bulk, both the generation and review of the reports becomes a major endeavor. We're currently using GP9, with plans to go to 10 this year. Thanks, Jeremy Hi Jeremy Have you looked at the Rockton Software add-on called Security Auditor? I think it will do everything you are looking for and more. -- Fliehigh &q...

CRM 1.2 SBS 2003 Can not install exchange email router
Logged on as domain admin throughout. Installed CRM successfully, followed install instructions, did not install to local host installed web to a hostheader of "companyweb" port 80. during Exchange email router setup I get an error when specifying CRM server and web - "one or more os the MS CRM servers you listed is invalid or you do not have administrator priveleges on that server...." server name: sbssrb01 web http://companyweb If I go into IIS can not open CRM web get - http Error 403 - Forbidden: Access is denied. All services are on 1 server "sbssrv01&qu...

Can I print one page landscape and the next page portrait on same.
I am trying to print the 3 pages of one worksheet and can not figure out how to make page one print out as landscape, page 2 to print out as portrait and page 3 to print out as landscape. I'd record a macro when I printed page 1 as landscape, then page 2 as portrait and then page 3 as landscape. So I could just rerun that macro when I needed it. lisajillian wrote: > > I am trying to print the 3 pages of one worksheet and can not figure out how > to make page one print out as landscape, page 2 to print out as portrait and > page 3 to print out as landscape. -- Dave Pet...