473,386 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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 3374
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 ProgressEventHandler(object sender, ProgressEventArgs
e);

public class MyClass
{
public event ProgressEventHandler Progress;

public void DoWork()
{
WebRequest request = WebRequest.Create(new
Uri("http://www.cnn.com"));
request.BeginGetResponse(new AsyncCallback(WorkCallback), request);
}

public void WorkCallback(IAsyncResult result)
{
WebRequest request = (WebRequest)result.AsyncState;
WebResponse response = request.EndGetResponse(result)

// This event is still being raised on the main thread.
if(Progress != null)
Progress(this, new ProgressEventArgs()):
}
}
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**********@REMOVETHIShotmail.com> wrote in message
news:y_Tdc.6363$es.1144@fed1read02...
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 ISynchronizeInvoke, 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
ISynchronizeInvoke).

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.Threading;

public class MyClass
{

public void DoWork()
{
WebRequest request = WebRequest.Create(new Uri("http://www.cnn.com"));
request.BeginGetResponse(new AsyncCallback(WorkCallback), request);
Console.WriteLine("Began request, sleeping 5 seconds");
Thread.Sleep(5000);
Console.WriteLine("Finished sleeping");

}

public void WorkCallback(IAsyncResult result)
{
WebRequest request = (WebRequest)result.AsyncState;
WebResponse response = request.EndGetResponse(result);

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

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

}
}


"Jacob" <ja**********@REMOVETHIShotmail.com> wrote in message
news:SpUdc.6366$es.857@fed1read02...
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 ProgressEventHandler(object sender, ProgressEventArgs
e);

public class MyClass
{
public event ProgressEventHandler Progress;

public void DoWork()
{
WebRequest request = WebRequest.Create(new
Uri("http://www.cnn.com"));
request.BeginGetResponse(new AsyncCallback(WorkCallback), request); }

public void WorkCallback(IAsyncResult result)
{
WebRequest request = (WebRequest)result.AsyncState;
WebResponse response = request.EndGetResponse(result)

// This event is still being raised on the main thread.
if(Progress != null)
Progress(this, new ProgressEventArgs()):
}
}
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**********@REMOVETHIShotmail.com> wrote in message
news:y_Tdc.6363$es.1144@fed1read02...
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**************@TK2MSFTNGP10.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 ISynchronizeInvoke, 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
ISynchronizeInvoke).

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.Threading;

public class MyClass
{

public void DoWork()
{
WebRequest request = WebRequest.Create(new Uri("http://www.cnn.com"));
request.BeginGetResponse(new AsyncCallback(WorkCallback), request);
Console.WriteLine("Began request, sleeping 5 seconds");
Thread.Sleep(5000);
Console.WriteLine("Finished sleeping");

}

public void WorkCallback(IAsyncResult result)
{
WebRequest request = (WebRequest)result.AsyncState;
WebResponse response = request.EndGetResponse(result);

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

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

}
}


"Jacob" <ja**********@REMOVETHIShotmail.com> wrote in message
news:SpUdc.6366$es.857@fed1read02...
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 ProgressEventHandler(object sender, ProgressEventArgs e);

public class MyClass
{
public event ProgressEventHandler Progress;

public void DoWork()
{
WebRequest request = WebRequest.Create(new
Uri("http://www.cnn.com"));
request.BeginGetResponse(new AsyncCallback(WorkCallback),

request);
}

public void WorkCallback(IAsyncResult result)
{
WebRequest request = (WebRequest)result.AsyncState;
WebResponse response = request.EndGetResponse(result)

// This event is still being raised on the main thread.
if(Progress != null)
Progress(this, new ProgressEventArgs()):
}
}
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**********@REMOVETHIShotmail.com> wrote in message
news:y_Tdc.6363$es.1144@fed1read02...
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
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...
0
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...
3
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...
4
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...
5
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...
7
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...
2
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....
2
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...
3
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...
0
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...

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.