473,806 Members | 2,782 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is there any easy scheme for handling event from another thread thanthe UI?

Hello.

Event handlers for events from an object of another thread than the UI
thread cannot access UI components, as you know. If the object has
many events this precedure is painstaking. Plus the source code gets
longer and dirtier.

Note :The code below is NOT the actual code, but an example. (I say
this, because sometimes people points out that the sample code won't
complie, even if it's just an example to explain the matter. ... means
there are more codes but are omitted because those are unnecessary.)

public delegate void MessageDelegate (Worker sender, Data d);
class ObjectFromAnoth erThread
{
public event MessageDelegate MessageReceived ;
....
MessageReceived (this, d);
....
}
class MainForm:Form
{
....
void OnMessage(Worke r sender, Data d)
{
if (InvokeRequired )
{
OnMessageDelega te d = new OnMessageDelega te(OnMessage);
this.BeginInvok e(d, new object[] { sender, d });
}
else
{
TheLabel.Text=d .ToString();
}
}
....
}

For example, if there are three events I have to write codes like
above three times. Am I using a wrong scheme? Is there any nicer,
cleaner way? I hope that I could hear some advices from you. Thank you.
Jun 27 '08 #1
4 1446
On Jun 5, 5:48 pm, Sin Jeong-hun <typing...@gmai l.comwrote:
Event handlers for events from an object of another thread than the UI
thread cannot access UI components, as you know. If the object has
many events this precedure is painstaking. Plus the source code gets
longer and dirtier.
As Peter Duniho has pointed out various times, there's little cost in
calling Invoke or BeginInvoke when you don't have to. Now, combine
that fact with the way that often your logic doesn't actually *need*
the sender (or logically always casts) it - and anonymous methods or
lambda expressions. Change the event subscription code to:

ObjectFromAnoth erThread.Messag eReceived += (sender, d) =>
BeginInvoke(OnM essage(d));

void OnMessage(Data d)
{
TheLabel.Text=d .ToString();
}

Nice and straightforward :)

It's slightly messier in C# 2 with anonymous methods, but still not
too bad.

Jon
Jun 27 '08 #2
On Jun 6, 1:59*am, "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
On Jun 5, 5:48 pm, Sin Jeong-hun <typing...@gmai l.comwrote:
Event handlers for events from an object of another thread than the UI
thread cannot access UI components, as you know. If the object has
many events this precedure is painstaking. Plus the source code gets
longer and dirtier.

As Peter Duniho has pointed out various times, there's little cost in
calling Invoke or BeginInvoke when you don't have to. Now, combine
that fact with the way that often your logic doesn't actually *need*
the sender (or logically always casts) it - and anonymous methods or
lambda expressions. Change the event subscription code to:

ObjectFromAnoth erThread.Messag eReceived += (sender, d) =>
BeginInvoke(OnM essage(d));

void OnMessage(Data d)
{
* * *TheLabel.Text= d.ToString();

}

Nice and straightforward :)

It's slightly messier in C# 2 with anonymous methods, but still not
too bad.

Jon
Thank you. Could you please tell me how to write the code above in C#
2.0 syntax? Because I mostly use C# 2.0 (I'ld like to use the latest
version but there are more chances that .NET Framework 2.0 is
installed on the client system than 3.0 is.)
Jun 27 '08 #3
Something like:

ObjectFromAnoth erThread.Messag eReceived += delegate
(object sender, Data d) {BeginInvoke(On Message(d));};

Marc
Jun 27 '08 #4
On Jun 6, 2:06 pm, Sin Jeong-hun <typing...@gmai l.comwrote:
It's slightly messier in C# 2 with anonymous methods, but still not
too bad.

Thank you. Could you please tell me how to write the code above in C#
2.0 syntax? Because I mostly use C# 2.0 (I'ld like to use the latest
version but there are more chances that .NET Framework 2.0 is
installed on the client system than 3.0 is.)
Marc has provided the C# 2 syntax, but it's important to understand
that you can still use C# 3 but target .NET 2.0. It's really nice to
have lambda expression goodness (and the rest) but still target the
more widely deployed framework.

See http://csharpindepth.com/Articles/Ch.../Versions.aspx for more
details.

Jon
Jun 27 '08 #5

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

Similar topics

2
4403
by: Michael Zhang | last post by:
My project uses Python-2.3.4 + Tkinter + PIL-1.1.4 to retrieve images from server and display those images. I created a thread (also a separate toplevel window) for displaying images and another thread for recording the frame rates (using a progress bar for visulization). The whole application worked very well once it received image data from the socket. The problem is when I tried to close that display window (click on the standard...
7
6010
by: Noor | last post by:
please tell the technique of centralize exception handling without try catch blocks in c#.
5
2600
by: Bill Davidson | last post by:
Hello All: I've got a question about synchronization requiremements in a C# worker thread procedure that, among other things, sinks events from outside sources. I realize the worker thread will be interrupted to handle an incoming event (and the flow of execution subsequently diverted to the respective event handler). My question is at what point or points could this interruption occur. Will it only occur when the worker thread is...
4
297
by: michaeltorus | last post by:
Hi I've written a custom Error handler thingy majig. I create it at the ASP level, and pass it into my business components which catch all errors below that. When an error occurs, my error handler onject fire and event, which the ASP.Net page is listening for. What I want to know is, does this mean that my error handling on the ASP page is effectivley done on another thread? Are there any risks in doing it this way? Cheers
4
1199
by: dave_wurtz | last post by:
All, First a little information... I have a class library that was developed for a GUI application that I am trying to get to work on my ASP.NET application. The library essentially is used to query a SQL database. It build the SQL Select statement based on specified criteria and submits it to the database. The statement is run on its own thread and when results are returned, it fires an event, passing a dataset of information as one...
12
2826
by: scsharma | last post by:
Hi, I am working on creating a webapplication and my design calls for creating main webform which will have menu bar on left hand side and a IFrame which will contain all the forms that are shown when menu items are clicked.Besides these i would like to put a custom status bar. Any error message encountered in any of the webpage will be displayed in the banner. The problem iam encountering is how to access the customer status bar in child...
12
4147
by: Jack Russell | last post by:
My unstanding of all VB up to and including vb6 is that an event could not "interrupt" itself. For instance if you had a timer event containing a msgbox then you would only get one message. However in vb.net you get continual messages (even setting the system modal property). Firstly, are these two assumptions right and if so what is the approved
2
2137
by: Paul E. Orman | last post by:
I have a piece of VB code (.NET 1.1 - VB 2003) that loads data from a database through a timer. So the timer is setup and from it I call the procedure that loads the latest records from the database. This works fine. However, I attempt to notify the user when data accesses occur. The way I attempt to accomplish this is by changing the background color of a label on the form the user is looking at. I use red for when the database is...
2
2843
by: Jordan | last post by:
I need to handle UI events in a worker thread instead of the primary UI thread. In C#, is the normal UI event handling behavior to run in a context thread on the thread pool or are events always invoked on the primary UI thread? Thanks, Jordan
0
9598
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10623
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10371
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10373
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
7650
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6877
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5546
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5683
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4330
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

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.