473,582 Members | 3,083 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

'cross-thread operation not valid' exception / multithreaded compo

Hello,

There are several 'cross-thread operation not valid' exception postings in
the MSDN discussion groups, but none address my exact situation.

I have authored a .NET component in Visual C# .NET 2003 that is capable of
firing several types of events to notify user of errors, data changes, etc.
The component uses a thread to perform background communications and if there
is an error or data-change fires an event to notify the user. If the
developer that is using my component wishes to display the value form
control's Text property, the 'cross-thread operation not valid' exception is
thrown in VS.NET 2005.

I understand why it is thrown (worker thread not allowed to update UI
thread), but can't find any definitive information on whether this is
addressable from the component standpoint, rather than requiring my
component's user to use delegates and IsInvokeRequire d/Invoke to display the
values.

Any feedback or suggestions would be appreciated.
Apr 8 '06 #1
11 8669
No, it's not necessary to require the user of the component to use
delegates, or any of that stuff. It is entirely possible to hide the
threading from the user, and the form in which the component is hosted.
Remember that the component itself resides in the same thread as the form.
It is the thread spawned by the component which is in another thread. As
long as your component itself manages the marshalling internally and fires
the event in the form's thread, it should not be a problem.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.

"HairlipDog 58" <Ha********@nos pam.nospam> wrote in message
news:95******** *************** ***********@mic rosoft.com...
Hello,

There are several 'cross-thread operation not valid' exception postings in
the MSDN discussion groups, but none address my exact situation.

I have authored a .NET component in Visual C# .NET 2003 that is capable of
firing several types of events to notify user of errors, data changes,
etc.
The component uses a thread to perform background communications and if
there
is an error or data-change fires an event to notify the user. If the
developer that is using my component wishes to display the value form
control's Text property, the 'cross-thread operation not valid' exception
is
thrown in VS.NET 2005.

I understand why it is thrown (worker thread not allowed to update UI
thread), but can't find any definitive information on whether this is
addressable from the component standpoint, rather than requiring my
component's user to use delegates and IsInvokeRequire d/Invoke to display
the
values.

Any feedback or suggestions would be appreciated.

Apr 9 '06 #2
Dear Customer,

In addition to Kevin's suggestion, I think you may try to take a look at
the three articles below about how to update UI from another thread for
your reference.

Safe, Simple Multithreading in Windows Forms, Part 1
http://msdn.microsoft.com/library/de...us/dnforms/htm
l/winforms0611200 2.asp
Safe, Simple Multithreading in Windows Forms, Part 2
http://msdn.microsoft.com/library/de...us/dnforms/htm
l/winforms0816200 2.asp
Safe, Simple Multithreading in Windows Forms, Part 3
http://msdn.microsoft.com/library/de...us/dnforms/htm
l/winforms0123200 3.asp

As almost every winform related class is not thread-safe, we have to
marshal all the call on the winform thread.
The .Net provides a simple method, Control.Invoke will marshal the call
onto the thread where the Control is. Also we can use SendMessage to
marshal the call, which is what the Control.Invoke do.

Best regards,

Peter Huang

Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Apr 10 '06 #3
Hi Peter,

As a component, I don't have access to the target UI control and do not know
what type of control will be updated from the event sink.

The articles that you suggested all describe a monolithic application where
a thread is started in a Win Forms application, and the event sink has
knowledge of the type of Win form control that will be updated.

I started down the path that Kevin described, but I'm having trouble
figuring out how to notify my component from the worker thread that an event
needs to be fired. I've tried setting up a delegate and using BeginInvoke,
but the same exception is thrown.
Also we can use SendMessage to marshal the call, which is what the Control.Invoke do.


Can you elaborate on SendMessage usage in .NET?

Apr 10 '06 #4
Hi Kevin,

I started down the path that you described, but I'm having trouble figuring
out how to notify my component from the worker thread that an event needs to
be fired on the UI thread. I've tried setting up a delegate and using
BeginInvoke, but the same exception is thrown (presumably because
BeginInvoke creates a thread to perform its work).

Any suggestions on how to make the 'component manage the marshalling
internally'?

Thanks in advance.

"Kevin Spencer" wrote:
No, it's not necessary to require the user of the component to use
delegates, or any of that stuff. It is entirely possible to hide the
threading from the user, and the form in which the component is hosted.
Remember that the component itself resides in the same thread as the form.
It is the thread spawned by the component which is in another thread. As
long as your component itself manages the marshalling internally and fires
the event in the form's thread, it should not be a problem.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.


Apr 10 '06 #5
HairlipDog58 <Ha********@nos pam.nospam> wrote:
As a component, I don't have access to the target UI control and do not know
what type of control will be updated from the event sink.

The articles that you suggested all describe a monolithic application where
a thread is started in a Win Forms application, and the event sink has
knowledge of the type of Win form control that will be updated.
Well, *something* certainly needs to know what will be updated.
However, UI components can expose thread-safe methods which perform the
necessary marshalling to the UI thread themselves. They would naturally
know which UI control to do things with.
I started down the path that Kevin described, but I'm having trouble
figuring out how to notify my component from the worker thread that an event
needs to be fired. I've tried setting up a delegate and using BeginInvoke,
but the same exception is thrown.


Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 10 '06 #6
There's a really good series on this topic on the MSDN online library:

http://msdn.microsoft.com/library/de...ms06112002.asp
http://msdn.microsoft.com/library/en...asp?frame=true
http://msdn.microsoft.com/library/de...ms08162002.asp

In addition, if you're working with .Net platform 2.0, you might want to
have a look at the System.Componen tModel.Backgrou ndWorker class:

http://msdn2.microsoft.com/en-US/lib...undworker.aspx

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.

"HairlipDog 58" <Ha********@nos pam.nospam> wrote in message
news:F5******** *************** ***********@mic rosoft.com...
Hi Kevin,

I started down the path that you described, but I'm having trouble
figuring
out how to notify my component from the worker thread that an event needs
to
be fired on the UI thread. I've tried setting up a delegate and using
BeginInvoke, but the same exception is thrown (presumably because
BeginInvoke creates a thread to perform its work).

Any suggestions on how to make the 'component manage the marshalling
internally'?

Thanks in advance.

"Kevin Spencer" wrote:
No, it's not necessary to require the user of the component to use
delegates, or any of that stuff. It is entirely possible to hide the
threading from the user, and the form in which the component is hosted.
Remember that the component itself resides in the same thread as the
form.
It is the thread spawned by the component which is in another thread. As
long as your component itself manages the marshalling internally and
fires
the event in the form's thread, it should not be a problem.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.

Apr 10 '06 #7
Hi Peter,

I re-phrased this in attempt to clarify the situation:

F = Form class
C = Component class
T = Thread

1. C is a component used by F.
2. C has an event called MyEvent and property called MyInteger.
3. T is a worker thread started by C.
4. T performs interval-based work then needs to notify C that the work has
been performed.
5. C must then fire MyEvent to notify F that work has been completed.
6. F has an OnMyEvent handler that that needs to update a UI control with
the data contained in MyInteger.

The cross-thread exception occurs because T is a different thread than C
(which is in the same thread as F). So T cannot call a method on C that
causes an event to fire.

The question is, how can T notify C that it has completed its work, so that
C can fire an event to notify F that new data is available?

I've tried using a delegate and BeginInvoke with same problem results (I'm
guessing BeginInvoke also causes a thread to be created).

I have a small example project that demonstrates the problem, but it is too
big to post here.
Apr 11 '06 #8
Hi,

Thanks for your update.
So far one approach is as Kevin suggested, we can try to use
BackgroundWorke r.

As you said, the component as a different control, it did not implement
ISynchronizeInv oke, which did not support to marshal call across thread.
As I said before the Control.Invoke implement call across thread via
SendMessage which worked with Windows.

For Component that did not have window, it did not work.

So for your scenario, I think you may try redesign your component to have a
window.
1. Create a hidden windows form, so that we can call invoke on that form's
instance.
2. Try to pass the outside form into the component.
Best regards,

Peter Huang

Microsoft Online Community Support
=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Apr 11 '06 #9
I did some simple tests and determined that BackgroundWorke r solves the
problem when the component is used in Win Forms apps but doesn't work in
console/service apps. The thread works but notifications don't (no message
pump), so console/service apps need special handling.

Is there a way to determine whether the component is being used in a Win
Forms or console/service app?

Apr 18 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2041
by: Web Science | last post by:
Site and Features: http://www.eigensearch.com Search engine, eigenMethod, eigenvector, mathematical, manifolds, science, technical, search tools, eigenmath, Jacobian, quantum, mechanics, manifolds, science, physics, chemistry, law, legal, government, home, office, business, domain lookup, medical, travel, food, university students, searching,...
12
3855
by: * ProteanThread * | last post by:
but depends upon the clique: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=954drf%24oca%241%40agate.berkeley.edu&rnum=2&prev=/groups%3Fq%3D%2522cross%2Bposting%2Bversus%2Bmulti%2Bposting%2522%26ie%3DUTF-8%26oe%3DUTF-8%26hl%3Den ...
3
3091
by: rollasoc | last post by:
Hi, Doing a bit of system testing on a Windows 98 laptop. (.Net 1.1 app). Did a bit of testing. Loaded a previously saved file. A gray box appeared with the text and buttons all white rectangles with a big red cross in it. Pressed a button (the one I thought might be ok). My file appeared to load. Then when I clicked on any...
0
1877
by: Web Science | last post by:
Site and Features: http://www.eigensearch.com Search engine, eigenMethod, eigenvector, mathematical, manifolds, science, technical, search tools, eigenmath, Jacobian, quantum, mechanics, manifolds, science, physics, chemistry, law, legal, government, home, office, business, domain lookup, medical, travel, food, university students, searching,...
4
5564
by: David Peach | last post by:
Hello, hope somebody here can help me... I have a query that lists defects recorded in a user defined date range. That query is then used as the source for a Cross Tab query that cross-tabs count of defect type by calendar month. Defect types are stored in one table, defect transactions in another along with date etc. When I cross-tab the...
0
2047
by: Web Science | last post by:
Site and Features: http://www.eigensearch.com Search engine, eigenMethod, eigenvector, mathematical, manifolds, science, technical, search tools, eigenmath, Jacobian, quantum, mechanics, manifolds, science, physics, chemistry, law, legal, government, home, office, business, domain lookup, medical, travel, food, university students, searching,...
1
2755
by: Rob Woodworth | last post by:
Hi, I'm having serious problems getting my report to work. I need to generate a timesheet report which will contain info for one employee between certain dates (one week's worth of dates). I have a table containing records for each job done, the records contain date, employee name, job done (a code representing the type of job), cost code...
6
8610
by: Simon | last post by:
Hi All, An experiment i'm doing requires requires a synchronous cross-domain request, without using a proxy. I wondered if anyone had any ideas to help me achieve this. Below is what I have tried, including my conclusions/assumptions (which i'll happily be corrected on if it solves my problem!): The requirement not to use a proxy means...
6
5473
by: Bart Van der Donck | last post by:
Hello, I'm presenting my new library 'AJAX Cross Domain' - a javascript extension that allows to perform cross-domain AJAX requests. http://www.ajax-cross-domain.com/ Any comments or suggestions are welcome. --
6
3973
by: ampo | last post by:
Hello. Can anyone help with cross-domain problem? I have HTML page from server1 that send xmlHTTPRequest to server2. How can I do it? Thanks.
0
7809
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8312
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7920
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8183
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
3809
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3835
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2312
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1413
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1147
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.