基于WPF的Dispatcher应用及探讨(二)

来源:互联网 发布:php扩展开发中文教程 编辑:程序博客网 时间:2024/05/22 18:41

上一节中我们完成了第一步的CustomizeDispatcher的方法编写,不过犯了个很严重的错误,我们为什么要在dispatcher中再对线程进行BeginInvoke调用呢?异步中套异步,根本停不下来,因此这里我们完善了昨天的方法,并且加入了异常处理以及对整个线程组的控制:

  public List<Exception> exceptionList = new List<Exception>();        public bool CustomizeDispatcher(Action<bool> callbackAction, params Action[] actions)        {            Func<bool> function = new Func<bool>            (() =>            {                ParallelLoopResult result = Parallel.For(0, actions.Length,                    (int ac, ParallelLoopState state) =>                    {                        try                        {                            actions[ac].Invoke();                        }                        catch (Exception ex)                        {                            exceptionList.Add(ex);                        }                    });                return !exceptionList.Any();            });            callbackAction.Invoke(function.Invoke());            return !exceptionList.Any();        }    }

Exception具体如何处理,还需要由需求决定,不过这里的概念就是成功完成了,就return true,否则就是false。

调用时我们只需传入个带参方法就可以了。

        static void Main(string[] args)        {            Run runmethod = new Run();            runmethod.CustomizeDispatcher(                complete=>                {                    if(complete) Console.WriteLine("Complete");                    else Console.WriteLine("Failed");                },                () =>                {                    Console.WriteLine(1);                    Thread.Sleep(10000);                },                () =>                {                    Console.WriteLine(2);                    Thread.Sleep(10000);                },                () =>                {                    Console.WriteLine(3);                    Thread.Sleep(10000);                },                () =>                {                    Console.WriteLine(4);                    Thread.Sleep(10000);                });            Console.WriteLine("Thread Complete");            Console.Read();        }

这样就初步完成了一开始的需求,具体还需要怎么样修改,需要到我们的架构中进行实际使用了。

0 0