相关疑难解决方法(0)

带事件通知的任务 - .net 4

昨天在SO上,我看到一个线程要求代码,其中一些是这样做的.我的意思是,您(经理线程)使用TPL API启动任务数量,一旦完成作业,该线程应通知您(经理)回复谁维护任务池.

所以这是我试过的代码.虽然我必须说它的工作原理如上所述.

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 …
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading task-parallel-library

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

.net ×1

c# ×1

multithreading ×1

task-parallel-library ×1