Control.BeginInvoke Execution Order

浪尽此生 提交于 2019-12-11 20:05:40

问题


When calling BeginInvoke(), will the delegates comes back in the same order that the method is being called? or there is no guarantee which delegates will come back first?

    public Form1()
    {
        InitializeComponent();

        for (int i = 0; i < 100; i++)
        {
            Thread t = new Thread(DisplayCount);
            t.Start(i);
        }
    }

    public void DisplayCount(object count)
    {
        if (InvokeRequired)
        {
            BeginInvoke(new Action<object>(DisplayCount), count);
            return;
        }

        listBox1.Items.Add(count);
    }

And list of integers will come back out of order.


回答1:


Control.BeginInvoke() will execute the action asynchronously, but on the UI thread.

If you call BeginInvoke() multiple times with different actions, they will come back in order of whichever ones complete the fastest.

As a side-note, you should probably use some sort of snychronization mechanism around your listBox1.Items.Add(count) calls, perhaps locking on its SynchRoot property.

From MSDN - ListBox.ObjectCollection Class

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

(Emphasis added)




回答2:


If you call the same function multiple times, then they should come back in the same order, maybe! If you have a function analysing a 1 TB Dataset and another function just doing some Logging then I don't think they will came back in the same order. It also depends on the DispatcherPriority you have set for BeginInvoke. A low priority like SystemIdl will be executet later then a higher priority like Send.




回答3:


If you start a thread using Thread.Start() then the execution of the Thread-Function happens asynchronously at a random time after that call. That's why you get random numbers in my opinion.



来源:https://stackoverflow.com/questions/10952711/control-begininvoke-execution-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!