Windows Service Threading

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

All,

I have a windows service that creates a couple of worker threads to do some processing. The service works fine.

However, the main service thread has a method for sending email notices that I would like to be able to call from the worker threads. Furthermore, I would like this call to be done asynchronously.

If I was working with a Windows Form app I would have no problem as the Form has a begin invoke method that works great for this. However, I can't find a similar method on the service.

How can I implement this scenario in a service application?

Thanks for the help!

Dan
 
Create a work queue. When a thread wants to send an email, write the object
the queue and keep going. The email thread will block waiting on some
objects in the queue and pop them off and send them. Your worker could also
just call the thread pool passing the object which will call your delegate
to do the sending on another thread. I like the queue method, but what ever
works for you.

--
William Stacey, MVP

Dan said:
All,

I have a windows service that creates a couple of worker threads to do
some processing. The service works fine.
However, the main service thread has a method for sending email notices
that I would like to be able to call from the worker threads. Furthermore, I
would like this call to be done asynchronously.
If I was working with a Windows Form app I would have no problem as the
Form has a begin invoke method that works great for this. However, I can't
find a similar method on the service.
 
Hi,

I also agree with the queue idea, it's VERY easy to implement, just
remember to Sync the queue, you do this by using Queue.Synchronized( )
This will make sure that the queue operations are thread safe.

Cheers,
 
:) I also like using a blocking queue so your thread blocks until some data
arrives. The default queue does not allow this behavior.
 
<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.machin AT
dot.state.fl.us> said:
I also agree with the queue idea, it's VERY easy to implement, just
remember to Sync the queue, you do this by using Queue.Synchronized( )
This will make sure that the queue operations are thread safe.

Well, it makes sure that any individual queue operation is thread-safe.
It doesn't mean that any *sequence* of queue operations is thread-safe.
For instance, if you do:

if (queue.Count != 0)
{
return queue.Dequeue();
}

then another thread could dequeue between the Count test and the
Dequeue call, so you could end up with an InvalidOperationException
being thrown.

I personally prefer to do the locking myself, explicitly, in code - I
find it more obvious what's going on that way.
 
when
Queue SQ = new Queue().Synchronized();
then
SQ.Enqueue(...) and SQ.Dequeue()
can be called at the same time from different threads?

- Joris
 
Back
Top