简体   繁体   English

在C#中尝试多线程

[英]Trying MultiThread in C#

I just wanted to try MultiThreading applications and check for how the performance would be if use multithread. 我只是想尝试多线程应用程序,并检查使用多线程的性能如何。

But I don't know either I did it wrong or I misunderstand it! 但是我不知道我做错了还是误会了! I'm amateur or even beginner in Programming. 我是编程的业余爱好者,甚至是初学者。

Because in Normal Mode(Without using Thread) it takes lower time to finish the process! 因为在普通模式下(不使用线程),花费更少的时间来完成该过程! for example: 例如:

With Using Thread: 02.8500253 But Without Using Thread: 02.5455425 使用线程:02.8500253,但不使用线程:02.5455425

Sometimes larger difference! 有时差异更大!

my question is: Have I done it wrong or i misunderstood multithreading or etc. i wanted to know what's wrong? 我的问题是:我做错了还是我误解了多线程等?我想知道什么地方出了问题? why without thread is faster here!? 为什么没有线程在这里更快呢?

Here's whole Code: 这是完整的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
namespace WindowsFormsApplication57
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    Stopwatch sw = new Stopwatch();

    private void button1_Click(object sender, EventArgs e)
    {
    //    System.Windows.Forms.Timer mytimer = new System.Windows.Forms.Timer();
   //     mytimer.Interval = 1;
        sw.Reset();

        sw.Start();

        Thread thread1 = new Thread(new ThreadStart(myfunction));
        thread1.Start();
        Thread thread2 = new Thread(new ThreadStart(myfunction));
        thread2.Start();

       // sw.Stop();
      //  for (int i = 0; i < mylist.Count; i++) 
     //   {
    //        listBox1.Items.Add(mylist[i]);
    //    }
        //listBox1.Items.Add
        //label1.Text = string.Format("Elapsed Time Using MultiThread= {0}", sw.Elapsed);

   //     mytimer.Enabled = true;
    }

    List<string> mylist = new List<string>();

    void myfunction()
    {    

        for (int i = 0; i < 10000; i++) 
        {
            mylist.Add(i.ToString());

     //       listBox1.Items.Add(i);
            if (listBox1.InvokeRequired)
            {
                listBox1.Invoke(new MethodInvoker(delegate { listBox1.Items.Add(i); }));
            }
            else { listBox1.Items.Add(i); }
        }
        if (mylist.Count == 20000)
        {
            sw.Stop();
            if (label1.InvokeRequired)
            {
                label1.Invoke(new MethodInvoker(delegate { label1.Text = string.Format("Elapsed Time Using MultiThread= {0}", sw.Elapsed); }));
            }
            else
            {
                label1.Text = string.Format("Elapsed Time Using MultiThread= {0}", sw.Elapsed);
            }
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        //Stopwatch sw = new Stopwatch();
        sw.Reset();
        sw.Start();

        myfunction();
        myfunction();

        //sw.Stop();
    //    for (int i = 0; i < mylist.Count; i++)
    //    {
   //         listBox1.Items.Add(mylist[i]);
   //     }
        label1.Text = string.Format("Elapsed Time WITHOUT MultiThread= {0}", sw.Elapsed);
    }

    private void button3_Click(object sender, EventArgs e)
    {
        mylist.Clear();
        listBox1.Items.Clear();
    }

}
}

Multithreads does not necessarily run faster than a single thread, remember creating/scheduling threads takes many CPU cycles. 多线程不一定比单线程运行得快,请记住创建/调度线程需要很多CPU周期。 For example, if you run your code in a single core CPU, multithreads actually makes it slower - although single core CPU is not common on modern PCs. 例如,如果您在单核CPU中运行代码,则多线程实际上会使速度变慢-尽管单核CPU在现代PC上并不常见。

Adding 20000 strings into mylist takes only a few milliseconds, 99% of CPU time is spent on listBox1.Invoke . 将20000个字符串添加到mylist仅需几毫秒, listBox1.Invoke花费了99%的CPU时间。

In your code, you call listBox1.Invoke to marshal to the call to UI thread, so the code listBox1.Items.Add(i); 在您的代码中,您调用listBox1.Invoke以编组对UI线程的调用,因此代码listBox1.Items.Add(i); from both threads is eventually running on the same UI thread , in this way there is no significant improvement (if any) over running on a single thread. 这两个线程最终都在同一个UI线程上运行,因此,与在单个线程上运行相比,没有明显的改进(如果有)。

You can try this listBox1.Items.AddRange(mylist) , this is only called once, instead of 20000 times. 您可以尝试使用此listBox1.Items.AddRange(mylist) ,它仅被调用一次,而不是20000次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM