Dispatcher Threads

B

buells

Hello Group,

I'm pretty new to C-Sharp, so perhaps it's a well known problem and i
didn't get the right words to search for in google etc.

My Problem is: I wrote (well adopted it from Java) a Dispatcher Thread,
which is 1. a singleton and 2. it should be started from the main and
then wait for DispatcherTasks to work on.

A simple usage would be:

Dispatcher.start();
DispatcherTask loTask = new MyDispatcherTask(); // subclasses
DispatcherTask
Dispatcher.addTask(loTask);

To that point everything works well, but when the main finishes, the
Dispatcher Thread should finish too, but it is still waiting for new
Tasks. In Java it worked all right, but in C# the Dispatcher Thread
never finishes. I think it is all right, that it doesn't finish, but
that is not the intended use ... How do i configure the Dispatcher
Thread, that it finishes, when the Main finishes (perhaps it should
finish the work on the current Task, but finish afterwards)

Thx in advance, Nils Drews

using System;
using System.Threading;
using System.Collections;
using Framework.DispatcherSystem;
using NSpring.Logging;
namespace Framework.DispatcherSystem.Engine
{
/// <summary>
/// Summary description for Dispatcher.
/// </summary>
public class Dispatcher
{
private Logger logger =
Logger.CreateFileLogger("E:\\temp\\nspring.log");
private static Dispatcher singleton = null;
private Queue queue = new Queue();
private Thread thread = null;
private Dispatcher()
{
thread = new Thread(new ThreadStart(run));
}

public static Dispatcher getInstance()
{
if (singleton == null)
{
singleton = new Dispatcher();
}
return singleton;
}

public void start()
{
thread.Start();
}

private void run()
{
while (true)
{
while(queue.Count != 0)
{
DispatcherTask loTask = (DispatcherTask) queue.Dequeue();
try
{
loTask.execute();
} catch (Exception e)
{
logger.Open();
logger.Log(e);
}
}

lock (queue)
{
try
{
if (queue.Count == 0)
{
Monitor.Wait(queue);
}
}
catch (Exception e)
{
logger.Open();
logger.Log(e);
}
}
}
}

private void addTask(DispatcherTask poTask)
{
lock(queue)
{
queue.Enqueue(poTask);
Monitor.Pulse(queue);
}
}

public static void addDispatcherTask(DispatcherTask poTask)
{
getInstance().addTask(poTask);
}
}
}
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Use Thread.IsBackground = true; for the worker thread


cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top