Control.BeginInvoke执行顺序 [英] Control.BeginInvoke Execution Order

查看:114
本文介绍了Control.BeginInvoke执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调用BeginInvoke()时,委托将以与调用该方法相同的顺序返回吗?还是不能保证哪个代表会首先回来?

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.

推荐答案

Control.BeginInvoke() 将异步执行操作,但在UI线程上执行。

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

如果您以不同的操作多次调用 BeginInvoke(),它们将以完成的顺序返回

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

作为旁注,您可能应该在 listBox1.Items.Add(count)<周围使用某种同步机制。 / code>调用,可能会锁定其 SynchRoot 属性。

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.

来自 MSDN-ListBox.ObjectCollection类


此类型的任何公共静态(在Visual Basic中为Shared)成员都是
线程安全的。不保证任何实例成员都是线程
的安全对象

(添加了强调)

这篇关于Control.BeginInvoke执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆