C#:Delegates和dynamicInvoke

时间:2011-11-23 13:27:36

标签: c# multithreading delegates

此代码:

public static class MulticastDelegateExtensions
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    public static void InvokeAllAsync(this MulticastDelegate d, params object[] args)
    {
        try
        {
            var x = d.GetInvocationList().ToList();
            Parallel.ForEach(x, (item) => item.DynamicInvoke(args));
        }
        catch (Exception e)
        {
            _logger.Fatal("Error while InvokeAllAsync... Should not happen!!", e);
        }
    }
}

用法:

    protected delegate void PriceUpdated(string exchangeName, string commodityName, string contractDate, PriceStruct data);
    protected event PriceUpdated PriceUpdatedEvent;
    protected void cbPriceUpdate(ref ExchangeStruct data)
    {
        if (PriceUpdatedEvent != null)
            PriceUpdatedEvent.InvokeAllAsync(data.ExchangeName, data.CommodityName, data.ContractDate, pricedetail);
    }

偶尔会失败:

TaskSchedulerException:{"An exception was thrown by a TaskScheduler."}

{"Value to add was out of range.\r\nParameter name: value"}

       at System.Threading.Tasks.Task.InternalRunSynchronously(TaskScheduler scheduler)
       at System.Threading.Tasks.Task.RunSynchronously(TaskScheduler scheduler)
       at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
       at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IList`1 list, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
       at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
       at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, Action`1 body)
       at XXX.Extensions.MulticastDelegateExtensions.InvokeAllAsync(MulticastDelegate d, Object[] args) in C:\XXX\Extensions\MulticastDelegateExtensions.cs:line 20

任何想法为什么以及如何让这些东西线程安全?或者至少有一些更详细的错误?

THX

1 个答案:

答案 0 :(得分:0)

你读过内部异常吗?您的某个事件侦听器中可能存在错误。

  

要添加的值超出范围

DateTime.Add()错误。