Safe Multi Threading
I am using the code below to run work in multiply threads. A client registers a callback and an input, and it is executed on the thread pool.
I have some notes about this code below:
public class WorkManager<T> : IWorkManager<T>
{
static ILog logger = LogManager.GetLogger(typeof(WorkManager<T>));
/// <summary>
/// I hate XML Comments, can't use generics in them.
/// </summary>
/// <param name="state">State is KeyValuePair<Action<T>,T></param>
private void ExecuteWorkThreaded(object state)
{
KeyValuePair<Action<T>, T> pair = (KeyValuePair<Action<T>, T>)state;
Action<T> action = pair.Key;
logger.DebugFormat("Executing action: {0}.{1}", action.Method.DeclaringType, action.Method.Name);
// this should prevent parallel execution of the same method from the same object
// and help prevent re-entracy issues.
lock (action)
{
try
{
action(pair.Value);
}
catch (Exception e)
{
logger.Error(string.Format("Exception when executing work on {0}.{1}",
action.Method.DeclaringType, action.Method.Name), e);
EventHandler<EventArgs<Exception>> temp = ExceptionRaised;
if (temp != null)
temp(this, new EventArgs<Exception>(e));
}
}
}
public void ExecuteWork(Action<T> action, T item)
{
KeyValuePair<Action<T>, T> pair = new KeyValuePair<Action<T>, T>(action, item);
AbortableThreadPool.QueueUserWorkItem(ExecuteWorkThreaded, pair);
}
public event EventHandler<EventArgs<Exception>> ExceptionRaised;
}
I am using the command patten here, where an object perform a single task, so I don't run into issues with two threads running actions from the same object. The object may be registered twice, but that is okay, we are serializing access to the action, so it wouldn't run in parallel. The only requirement that I have from my actions is that they can be called more than once, which is a lot less than require them to be thread safe.
The whole idea here is to save threads. I don't want my threads to be busy waiting for something, and I do want centralized control over how they are executed and why. As I said, the logging is extremely important to me, but it also something that I would like to free the actions from (except action related logging, of course.
Comments
Comment preview