在两个线程中填充组合框比在一个线程中慢

时间:2015-12-30 09:19:41

标签: c# multithreading winforms combobox

我有以下代码来填充两个不同的组合框,它们具有来自数据表的相同值。使用2个线程需要3.29秒,使用一个线程需要2.668。

    public void InitWithThreads()
    {
        var masterItems = _items.GetListOfItems();

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        var thread1 = new Thread(() => PopulateCombobox(ItemComboBox, masterItems));
        thread1.Start();
        var thread2 = new Thread(() => PopulateCombobox(AlternateItemComboBox, masterItems.Copy()));
        thread2.Start();

        thread1.Join();
        thread2.Join();

        stopwatch.Stop();
        Text = stopwatch.Elapsed.ToString();
    }


    public void InitWithoutThread()
    {
        var masterItems = _items.GetListOfItems();

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        PopulateCombobox(ItemComboBox, masterItems);
        PopulateCombobox(AlternateItemComboBox, masterItems.Copy());

        stopwatch.Stop();
        Text = stopwatch.Elapsed.ToString();
    }

    private void PopulateCombobox(ComboBox combobox, DataTable datatable)
    {
        combobox.DisplayMember = "item";
        combobox.ValueMember = "item";

        combobox.DataSource = datatable;
    }

为什么使用线程更慢? 有没有办法阻止masterItems数据表的重复填充第二个组合框?

0 个答案:

没有答案