C#List作为BeginInvoke的委托

时间:2017-01-25 16:57:11

标签: c# list delegates begininvoke

我用这个撕掉了我的头发,我已经浪费了一天多的时间。我确定这是一些愚蠢的事情,而我根本没有足够的经验,所以非常感谢任何帮助!

这是交易......我有一个National Instruments Graph对象列表,我必须用新数据刷新。 这有意义吗?它适用于下面的代码,但显然只适用于一个图表。 问题是,如何传递图表列表而不是一个,然后循环它们以分配数据。 先感谢您!

    private void GetAndPlotData(Action<object> actionPlotData)
    {
        for (int ok = 0; ok < 10000000; ok++)
        {
            // Get some data here for every graph
            double[][] testData = new double[2][];
            testData[0] = new double[] { 1, 2, 3, 4 };
            testData[1] = new double[] { 2, 4, 6, 8 };

            // Plot it
            // QUESTION - how to reference passed List of Graphs in the loop to assign data?
            Dispatcher.BeginInvoke(actionPlotData, new object[] { testData });

            Thread.Sleep(10);
        }
    }

    private async void StartTest()
    {
        // QUESTION -  how to pass List Of Graphs as an Action to loop through them later on?
        await Task.Run(() => GetAndPlotData(data => Graphs[0].DataSource = data));
    }

1 个答案:

答案 0 :(得分:0)

我不确定我完全理解这个问题所以这是第一个提案,以便你可以解释这不是你想要的:)

private void GetAndPlotData(List<Action<object>> actionPlotData)
{
    for (int ok = 0; ok < 10000000; ok++)
    {
        // Get some data
        double[][] testData = new double[2][];
        testData[0] = new double[] { 1, 2, 3, 4 };
        testData[1] = new double[] { 2, 4, 6, 8 };

        // Plot it
        // QUESTION - how to reference passed List of Graphs in the loop?
        for (int i = 0; i < actionPlotData.Count; i++)
        {
            Dispatcher.BeginInvoke(actionPlotData[i], new object[] { testData[i] });
        }

        Thread.Sleep(10);
    }
}

private async void StartTest()
{
    // QUESTION -  how to pass List Of Graphs as an Action to loop through them later on?
    await Task.Run(() => GetAndPlotData( new List<Action<object>> { 
        data => Graphs[0].DataSource = data,
        data2 => Graphs[1].DataSource = data2
        });
}

动态列表的更新版本

    var actions = Graphs.Select(g => (Action<object>)(data => g.DataSource = data)).ToList();

    // QUESTION -  how to pass List Of Graphs as an Action to loop through them later on?
    await Task.Run(() => GetAndPlotData(actions));