473,549 Members | 2,595 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Make Thread-Safe Calls to Windows Forms Controls

Hello

I want to get the value of a property of a control from a thread other than the
thread the control was created on, as far as I can see this is not the same as
invoking an operation on a control on a different thread I have used the
following code as per the guidance in the msdn documentation to invoke an
operation on a control from a thread other than which it was created

delegate void SetFormCursorCa llback(Cursor cursor);

private void SetFormCursor(C ursor cursor)
{
if (this.InvokeReq uired)
{
SetFormCursorCa llback d = new
SetFormCursorCa llback(SetFormC ursor);
this.Invoke(d, new object[] { cursor });
}
else
{
this.Cursor = cursor;
}
}

What would I do if I wanted to access the Cursor property of the form and return
it to the caller on a different thread?

What techniques can I employ to do this?

Is there a way to make a synchronous call using a delegate that executes on a
different thread and then returns a value to the calling thread?

Thank you

Alex

Feb 9 '06 #1
7 17321
Hi Alexander,

Thanks for your post.

Based on my understanding, you want to know how to get the cursor value
from another thread.

In .Net, Property is just a set/get methods accessor wrapper , so we should
also obey the .Net winform threading safe rule. So you should use the same
way as the code snippet you posted to get the Form cursor value.(Note: get
the Form cursor value means invoking the get_PropertyNam e() method Form
class )

I have writen a little sample to demonstrate this technology:

void GetCursorValue( )
{
Cursor cs=this.Cursor;
MessageBox.Show (cs.ToString()) ;
}

void ThreadProc()
{
if(this.InvokeR equired)
{
this.Invoke(new MethodInvoker(G etCursorValue), null);
}
else
{
MessageBox.Show ("I am in UI thread, there is no need to do thread safe
operation!");
}
}
private void button1_Click(o bject sender, System.EventArg s e)
{
Thread t=new Thread(new ThreadStart(Thr eadProc));
t.Start();
}

Hope this helps!

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Feb 10 '06 #2
Hi Jeffrey

I have been able to access the value of a controls property from another thread
in a thread safe manner by invoking a delegate that returns a value, The problem
that I now face is where I return a reference type such as a collection and I
try to loop through the collection from the thread other than that on which the
collection was created.

In my specific case I have a background worker that performs a lengthy operation
where it makes several calls to a webservice whilst accessing the selected items
collection of a list view, it needs to read selected items and then add new
items to the list view, I can add items to the list view in a thread safe manner
without any problems, but when I try to loop through the selected items
collection of the listview i get an exception telling me that it is not thread
safe, even though I obtained the reference in a threadsafe manner

heres the code

delegate ListView.Select edListViewItemC ollection
GetSelectedList ViewItemsCallba ck();

private ListView.Select edListViewItemC ollection
GetSelectedList ViewItems()
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
//
if (this.itemListV iew.InvokeRequi red)
{
GetSelectedList ViewItemsCallba ck d = new
GetSelectedList ViewItemsCallba ck(GetSelectedL istViewItems);
return this.Invoke(d) as
ListView.Select edListViewItemC ollection;
}
else
{
return itemListView.Se lectedItems;
}

}

thanks

Alex
Feb 10 '06 #3
i think you can just access the property directly. as long as you
don't cause any changes to the UI which you are aware of already.
at least i have done this without any visible side-effects. i know you
can get away with bad multi-threading but you will sometimes see
strange things happening... this has never happened to me just by
reading a property of a control that was created on another thread.

tim

Feb 10 '06 #4

"Tim_Mac" <ma********@gma il.com> wrote in message
news:11******** *************@g 43g2000cwa.goog legroups.com...
|i think you can just access the property directly. as long as you
| don't cause any changes to the UI which you are aware of already.
| at least i have done this without any visible side-effects. i know you
| can get away with bad multi-threading but you will sometimes see
| strange things happening... this has never happened to me just by
| reading a property of a control that was created on another thread.
|
| tim
|

This is true, but (unfortunately) in v2 of the framework, you will get an
'illigal cross-thread call' exception thrown on you in debug mode. That
means that all cross-thread accesses to UI elements are considered bad
practice.

Willy.
Feb 10 '06 #5
if we're talking .net 2.0, i would use the BackgroundWorke r class and
pass in the cursor as the argument. if you are already using the
argument parameter, then send in an object array as the argument to the
RunWorkerAsync method, including the Cursor in the array. it is a
reference type so you should have a local/valid handle to it in the
worker thread.

hope this helps
tim

Feb 10 '06 #6

"Tim_Mac" <ma********@gma il.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
| if we're talking .net 2.0, i would use the BackgroundWorke r class and
| pass in the cursor as the argument. if you are already using the
| argument parameter, then send in an object array as the argument to the
| RunWorkerAsync method, including the Cursor in the array. it is a
| reference type so you should have a local/valid handle to it in the
| worker thread.
|
| hope this helps
| tim
|

I think you misunderstood or maybe I wasn't clear enough. I'm just replying
to yours :
<
....this has never happened to me just by reading a property of a control
that was created on another thread.

While it's perfectly valid to "read UI properties" in Windows, V2.0 of the
framework flags all UI accesses from non UI threads as illegal, which is not
true of course.

Willy.


Feb 10 '06 #7
Hi Alexander,

Thanks for your feedback.

Yes, I see your concern. This is because any manipulation to the UI thread
object from another thread needs to be marshalled with thread safe manner.
Regarding your scenario, we'd better place the loop through items code in a
method, then in the non-UI thread, we can use the Control.Invoke method to
invoke this method. Since the method code runs in the UI thread, no
marshaling is required in the method now.

Hope this helps

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Feb 13 '06 #8

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

Similar topics

10
3039
by: Berthold Hoellmann | last post by:
Hello, When I use ./configure --with-thread --with-fpectl --with-signal-module \ --with-pymalloc --enable-shared --with-cxx=g++ make test on 2.3.3 I get
2
5462
by: jam | last post by:
dear all, could anyone help me about telling me how can i make a background thread displaying loading... when I cam calling a console application?? thanks.. jam
4
1714
by: Manuel | last post by:
I have a long function that needs to be done 1000 times. I'm multithreading it, but I don't want to load them up all at once, instead load them 10 at a time. So far the only way I can get it to work is by creating a dummy form with a timer. On the timer function I test if the number of threads are less than 10 then run the remaining ones....
0
1075
by: Nick | last post by:
hi, I have a asp.net project. I want to start a thread in this project at some point to do some operations on database.Is there a limitation on this thread about how long it could run? Is it possible to make it run all the time to do monitor job? For me, looks like it works on my machine. But when I put it to the my webhost, public it,...
9
5516
by: zxo102 | last post by:
Hi everyone, I am using a python socket server to collect data from a socket client and then control a image location ( wxpython) with the data, i.e. moving the image around in the wxpython frame. But the "app.MainLoop()" in wxpython looks like conflicting with the "while 1:" in socket server. After I commented the "app.MainLoop()",...
5
7261
by: johnny | last post by:
Is there a way to call a function on a specified interval(seconds, milliseconds) every time, like polling user defined method? Thanks.
1
2281
by: Morgan Cheng | last post by:
I have one webservice that involves time-costing computation. For each request, it consumes about 2 seconds computation. Since ASP.NET has 25 threads per CPU to handle requests, this delay turns to be bottleneck if webservice is synchronous. Say, the webserivce is called ABC, then one thread is arranged for one call to ABC, and the thread is...
5
1295
by: fniles | last post by:
I am using VB.NET 2005. My program receives messages, and for every message I create a thread. Say I received Message 1, spawn the thread, then receive Message 2, spawn the thread. Even though I spawn the Message1 thread before Message2 thread, sometimes Message 2 thread is executed before Message 1 thread. Is there a way for me make sure...
82
3625
by: Bill David | last post by:
SUBJECT: How to make this program more efficient? In my program, a thread will check update from server periodically and generate a stl::map for other part of this program to read data from. Let's name the update method as doUpdate and stl::map read methods as getData and copyData. Since stl::map is not thread-safe, we should do...
0
7521
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7451
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...
1
7473
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
7810
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
6044
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5369
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
1
1944
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
1061
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
764
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.