Reputation: 9
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.
Upvotes: 0
Views: 1847
Reputation: 1
I could be wrong but Control.BeginInvoke() will preserve the order of the queued tasks as long as all executions are processed on the same thread, based on this discussions. With the UI thread established and active, the reordered numbers actually reflect the sequence how they are queued. In other words, the culprit is Thread.Start() which cannot guarantee a sequential order. The remarks of the official document should give a hint:
Once a thread is in the ThreadState.Running state, the operating system can schedule it for execution. The thread begins executing at the first line of the method represented by the ThreadStart or ParameterizedThreadStart delegate supplied to the thread constructor. Note that the call to Start does not block the calling thread.
I'm also a learner with UI and threading stuff so please correct me if I'm wrong!
Upvotes: 0
Reputation: 8037
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)
Upvotes: 1
Reputation: 687
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.
Upvotes: 0
Reputation: 891
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
.
Upvotes: 0