473,614 Members | 2,107 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Worker Threads and Events

I'm working on a class that needs to be called from a windows form, do it's
work, and then, show progress back to the main form. I'm well aware that
worker threads need to call Invoke for updates to the main thread to be
threadsafe. I want to make this worker class I'm writing a self contained
assembly so that other's can drop it into their projects. My question is:

How can I NOT force those implementing my class to have to call Invoke? Is
there a way I can do that within my class so that the progress returned is
safe to use on the main thread? What's the best way to signal that progress
has been made, an event? or some type of callback? Can I do this with
triggering an event from my worker class and listened to by the main thread,
or are events not threadsafe either?
Thanks for your help.

Jacob
Nov 16 '05 #1
3 3414
Never mind, I answered my own question. I realized that the class I'm
writing donsn't really try an make any calls back to the main thread on a
different thread. The class I wrote is handling threaded operations
asynchronously and only signalling events from the portions of the code that
are blocking. For example.

public delegate void ProgressEventHa ndler(object sender, ProgressEventAr gs
e);

public class MyClass
{
public event ProgressEventHa ndler Progress;

public void DoWork()
{
WebRequest request = WebRequest.Crea te(new
Uri("http://www.cnn.com"));
request.BeginGe tResponse(new AsyncCallback(W orkCallback), request);
}

public void WorkCallback(IA syncResult result)
{
WebRequest request = (WebRequest)res ult.AsyncState;
WebResponse response = request.EndGetR esponse(result)

// This event is still being raised on the main thread.
if(Progress != null)
Progress(this, new ProgressEventAr gs()):
}
}
I just realized that I'm actually sending the Progress event from a portion
of the code that is blocking. All the threaded work is going on between the
DoWork and WorkCallback methods, but calls within those methods should be
safe. So, implementers of my class should be able to subscribe to the
Progress event without fear that it will cause their main thread to throw an
exception. Correct me if I'm wrong.
Jacob


"Jacob" <ja**********@R EMOVETHIShotmai l.com> wrote in message
news:y_Tdc.6363 $es.1144@fed1re ad02...
I'm working on a class that needs to be called from a windows form, do it's work, and then, show progress back to the main form. I'm well aware that
worker threads need to call Invoke for updates to the main thread to be
threadsafe. I want to make this worker class I'm writing a self contained
assembly so that other's can drop it into their projects. My question is:

How can I NOT force those implementing my class to have to call Invoke? Is there a way I can do that within my class so that the progress returned is
safe to use on the main thread? What's the best way to signal that progress has been made, an event? or some type of callback? Can I do this with
triggering an event from my worker class and listened to by the main thread, or are events not threadsafe either?
Thanks for your help.

Jacob

Nov 16 '05 #2
First of all, I have an article based on an MSDN Magazine article that does
a log of what you are talking about. Have a look at these url's:

http://msdn.microsoft.com/msdnmag/is...g/default.aspx
http://www.mag37.com/csharp/articles...x.html?tabid=8

The idea in the above articles is that if the object subscribing to your
class' events implements ISynchronizeInv oke, then you can always send your
events back on the main thread of the subscriber. This method works well if
you know that the subscriber is a Control (since those all implement
ISynchronizeInv oke).

http://msdn.microsoft.com/library/de...classtopic.asp

Second, to answer your question, you are incorrect in your assumption below.
I've modified your program slightly to show this. You'll see the main thread
sleep 5 seconds after beginning the request. While the main thread is
sleeping, the second thread will complete the request and print something
to the screen. Only then will the first thread actually finish. (You might
need to change the delay to 10 seconds, depending upon how long it takes to
get the cnn.com request).

Hope that helps you out. If you have further questions, feel free to follow
up on this newsgroup.

Mike Mayer, C# MVP
mi**@mag37.com
http://www.mag37.com/csharp/

using System;
using System.Net;
using System.Threadin g;

public class MyClass
{

public void DoWork()
{
WebRequest request = WebRequest.Crea te(new Uri("http://www.cnn.com"));
request.BeginGe tResponse(new AsyncCallback(W orkCallback), request);
Console.WriteLi ne("Began request, sleeping 5 seconds");
Thread.Sleep(50 00);
Console.WriteLi ne("Finished sleeping");

}

public void WorkCallback(IA syncResult result)
{
WebRequest request = (WebRequest)res ult.AsyncState;
WebResponse response = request.EndGetR esponse(result) ;

// on 2nd thread
Console.WriteLi ne("Completed request");
}

public static void Main()
{
MyClass myclass = new MyClass();
myclass.DoWork( );

}
}


"Jacob" <ja**********@R EMOVETHIShotmai l.com> wrote in message
news:SpUdc.6366 $es.857@fed1rea d02...
Never mind, I answered my own question. I realized that the class I'm
writing donsn't really try an make any calls back to the main thread on a
different thread. The class I wrote is handling threaded operations
asynchronously and only signalling events from the portions of the code that are blocking. For example.

public delegate void ProgressEventHa ndler(object sender, ProgressEventAr gs
e);

public class MyClass
{
public event ProgressEventHa ndler Progress;

public void DoWork()
{
WebRequest request = WebRequest.Crea te(new
Uri("http://www.cnn.com"));
request.BeginGe tResponse(new AsyncCallback(W orkCallback), request); }

public void WorkCallback(IA syncResult result)
{
WebRequest request = (WebRequest)res ult.AsyncState;
WebResponse response = request.EndGetR esponse(result)

// This event is still being raised on the main thread.
if(Progress != null)
Progress(this, new ProgressEventAr gs()):
}
}
I just realized that I'm actually sending the Progress event from a portion of the code that is blocking. All the threaded work is going on between the DoWork and WorkCallback methods, but calls within those methods should be
safe. So, implementers of my class should be able to subscribe to the
Progress event without fear that it will cause their main thread to throw an exception. Correct me if I'm wrong.
Jacob


"Jacob" <ja**********@R EMOVETHIShotmai l.com> wrote in message
news:y_Tdc.6363 $es.1144@fed1re ad02...
I'm working on a class that needs to be called from a windows form, do

it's
work, and then, show progress back to the main form. I'm well aware that worker threads need to call Invoke for updates to the main thread to be
threadsafe. I want to make this worker class I'm writing a self contained assembly so that other's can drop it into their projects. My question is:
How can I NOT force those implementing my class to have to call Invoke?

Is
there a way I can do that within my class so that the progress returned is safe to use on the main thread? What's the best way to signal that

progress
has been made, an event? or some type of callback? Can I do this with
triggering an event from my worker class and listened to by the main

thread,
or are events not threadsafe either?
Thanks for your help.

Jacob


Nov 16 '05 #3
Thank you for that clearer explanation. I've actually read your MSDN
article several times before, but there's nothing like getting it from the
horse's mouth. :)
Jacob
"Michael Mayer [C# MVP]" <mi**@mag37.com > wrote in message
news:uc******** ******@TK2MSFTN GP10.phx.gbl...
First of all, I have an article based on an MSDN Magazine article that does a log of what you are talking about. Have a look at these url's:

http://msdn.microsoft.com/msdnmag/is...g/default.aspx
http://www.mag37.com/csharp/articles...x.html?tabid=8

The idea in the above articles is that if the object subscribing to your
class' events implements ISynchronizeInv oke, then you can always send your
events back on the main thread of the subscriber. This method works well if you know that the subscriber is a Control (since those all implement
ISynchronizeInv oke).

http://msdn.microsoft.com/library/de...classtopic.asp
Second, to answer your question, you are incorrect in your assumption below. I've modified your program slightly to show this. You'll see the main thread sleep 5 seconds after beginning the request. While the main thread is
sleeping, the second thread will complete the request and print something
to the screen. Only then will the first thread actually finish. (You might
need to change the delay to 10 seconds, depending upon how long it takes to get the cnn.com request).

Hope that helps you out. If you have further questions, feel free to follow up on this newsgroup.

Mike Mayer, C# MVP
mi**@mag37.com
http://www.mag37.com/csharp/

using System;
using System.Net;
using System.Threadin g;

public class MyClass
{

public void DoWork()
{
WebRequest request = WebRequest.Crea te(new Uri("http://www.cnn.com"));
request.BeginGe tResponse(new AsyncCallback(W orkCallback), request);
Console.WriteLi ne("Began request, sleeping 5 seconds");
Thread.Sleep(50 00);
Console.WriteLi ne("Finished sleeping");

}

public void WorkCallback(IA syncResult result)
{
WebRequest request = (WebRequest)res ult.AsyncState;
WebResponse response = request.EndGetR esponse(result) ;

// on 2nd thread
Console.WriteLi ne("Completed request");
}

public static void Main()
{
MyClass myclass = new MyClass();
myclass.DoWork( );

}
}


"Jacob" <ja**********@R EMOVETHIShotmai l.com> wrote in message
news:SpUdc.6366 $es.857@fed1rea d02...
Never mind, I answered my own question. I realized that the class I'm
writing donsn't really try an make any calls back to the main thread on a
different thread. The class I wrote is handling threaded operations
asynchronously and only signalling events from the portions of the code that
are blocking. For example.

public delegate void ProgressEventHa ndler(object sender, ProgressEventAr gs e);

public class MyClass
{
public event ProgressEventHa ndler Progress;

public void DoWork()
{
WebRequest request = WebRequest.Crea te(new
Uri("http://www.cnn.com"));
request.BeginGe tResponse(new AsyncCallback(W orkCallback),

request);
}

public void WorkCallback(IA syncResult result)
{
WebRequest request = (WebRequest)res ult.AsyncState;
WebResponse response = request.EndGetR esponse(result)

// This event is still being raised on the main thread.
if(Progress != null)
Progress(this, new ProgressEventAr gs()):
}
}
I just realized that I'm actually sending the Progress event from a

portion
of the code that is blocking. All the threaded work is going on between

the
DoWork and WorkCallback methods, but calls within those methods should be safe. So, implementers of my class should be able to subscribe to the
Progress event without fear that it will cause their main thread to throw an
exception. Correct me if I'm wrong.
Jacob


"Jacob" <ja**********@R EMOVETHIShotmai l.com> wrote in message
news:y_Tdc.6363 $es.1144@fed1re ad02...
I'm working on a class that needs to be called from a windows form, do it's
work, and then, show progress back to the main form. I'm well aware

that worker threads need to call Invoke for updates to the main thread to be threadsafe. I want to make this worker class I'm writing a self contained assembly so that other's can drop it into their projects. My question is:
How can I NOT force those implementing my class to have to call
Invoke? Is
there a way I can do that within my class so that the progress

returned is safe to use on the main thread? What's the best way to signal that

progress
has been made, an event? or some type of callback? Can I do this with
triggering an event from my worker class and listened to by the main

thread,
or are events not threadsafe either?
Thanks for your help.

Jacob



Nov 16 '05 #4

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

Similar topics

5
10656
by: fooooo | last post by:
This is a network app, written in wxPython and the socket module. This is what I want to happen: GUI app starts. User clicks a button to 'start' the work of the app. When start is pressed, a new thread is spawned (threading module) and this thread starts listening for data on a socket. When someone connects, a new thread is spawned, It needs to do I/O on that socket and open a GUI window so the user can communicate with the client...
0
1445
by: spammy | last post by:
Hi all, I have a windows form that uses an imported COM class to talk to a legacy system. The COM object works asynchronously - An event is fired when data has been returned. This works fine, except that Im getting too many events fired! Thus my windows form becomes pretty sluggish and unresponsive, and CPU utilistaion is pretty high.
3
506
by: Jacob | last post by:
I'm working on a class that needs to be called from a windows form, do it's work, and then, show progress back to the main form. I'm well aware that worker threads need to call Invoke for updates to the main thread to be threadsafe. I want to make this worker class I'm writing a self contained assembly so that other's can drop it into their projects. My question is: How can I NOT force those implementing my class to have to call...
4
2617
by: Brian Keating EI9FXB | last post by:
Hello there, Just a few questions re: worker theads. I have a worker thread that i wish to perform certain task. This worker thread must also handle events. Now my real questions..... What sort of ipc will i use between threads? (i used PostThreadMessage on win32)
5
2595
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...
7
2680
by: Charles Law | last post by:
My first thought was to call WorkerThread.Suspend but the help cautions against this (for good reason) because the caller has no control over where the thread actually stops, and it might have a lock pending, for example. I want to be able to stop a thread temporarily, and then optionally resume it or stop it for good.
2
4131
by: Tim | last post by:
The are 2 threads - main thread and worker thread. The main thread creates the worker thread and then the worker thread runs in an infinite while loop till it is asked to exit by setting an event. The worker thread instantiates an object and calls methods of that object. If some method call fails, the main thread needs to be notified about the failure. What mechanisms exist for notifying the main thread about the worker thread's status -...
2
2825
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
3
2296
by: Kevin | last post by:
Using this: http://msdn2.microsoft.com/en-us/library/3dasc8as(VS.80).aspx as an example I have a question concerning the reuse of objects. In the example 10 instances of the Fibonacci class are made and then all put in the threadpool at once, which is well within the limits of the threadpool. However, what happens if you want to do 10,000 Fibonacci calculations
0
1122
by: Stonepony | last post by:
Hi you all, I'm writing an application where I have a C# GUI. The applicaiton can start a lot of worker threads in unmanaged C++. To get progress events the worker threads calles methods that are implemented in CLI and it all goes up to C# where I use control.invoke(...) to change thread so that the GUI can be updated in the correct thread. Everything is fine. However, I also use some OpenGL stuff in C++ that intercepts the event and starts...
0
8182
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8130
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
8627
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...
1
8279
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,...
0
8433
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5540
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
4052
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...
1
1747
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1425
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.