Yesterday on SO, i saw a thread asking for a code which some what does this way. I mean, you (manager thread) start number of tasks using TPL APIs and once they are completed job, that thread should notify you (Manager) back who maintains Task pool.
So here is the code which i tried. Although i must say it works as i describe above.
class TaskJob
{
public delegate void NotificationDelegate(int? taskId,string message);
public event NotificationDelegate NotifyCompletion;
public void TaskToRun()
{
try
{
if (Task.CurrentId == 4)//If its a 4th thread, simulate exception
throw new Exception();
Console.WriteLine("Task started with thread id " + Task.CurrentId);
Thread.Sleep(100000);
Console.WriteLine("Task finished with thread id " + Task.CurrentId);
NotifyCompletion(Task.CurrentId, "Successfully completed");
}
catch
{
NotifyCompletion(Task.CurrentId, "Faulted error");
}
}
}
class Program
{
static List<Task> taskList = new List<Task>();
public static void Main()
{
for (int i = 0; i < 5; i++)//starting 5 threads/tasks
{
TaskJob tb = new TaskJob();
tb.NotifyCompletion += new ConsoleApplication1.TaskJob.NotificationDelegate(tb_NotifyCompletion);
Task t = Task.Factory.StartNew(tb.TaskToRun);
taskList.Add(t);
}
Task.WaitAll(taskList.ToArray());
CheckAndDispose();
Console.ReadLine();
}
private static void CheckAndDispose()
{
foreach (var item in taskList)
{
Console.WriteLine("Status of task = " + item.Id + " is = " + item.Status);
item.Dispose();
}
}
static void tb_NotifyCompletion(int? taskId, string message)
{
Console.WriteLine("Task with id completed ="+ taskId + " with message = " + message);
}
}
Couple of heads up:
Now i am asking myself couple of questions, but fail to convince myself with an suitable answer. Here are they:
Thanks alot :)
There's no need to do this yourself at all - use continuations with Task.ContinueWith
or Task<T>.ContinueWith
. That basically lets you say what to do when a task completes - including executing different code on failure, cancellation, and success.
It also returns a task, so you can then continue when that's completed etc.
Oh, and you can give it a TaskScheduler
, so that from a UI thread you can say, "When this background task finishes, execute the given delegate on the UI thread" or similar things.
This is the approach that C# 5 async methods are built on.
Alternatively you can try using async / await pattern. If you await a Task that means the compiler will automatically generate the ContinueWith for you.
If you use this pattern you can write normal async methods which will itself generate State machine.
Check my post
http://www.codeproject.com/KB/cs/async.aspx
Rx on the other hand can represent your data flow, I mean you can hook a sequence of jobs and subscribe your observable on an Observer.
http://msdn.microsoft.com/en-us/data/gg577609
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With