在C#中跨線程訪問Winform控制項

來源:互聯網
上載者:User
在程式需要讀取CAD檔案清單中的檔案資訊,這是一個非常費時的操作,所以希望通過多線程的方式來實現,並且可以隨時中止。由於初次使用多線程,開始的時候採用獨立的線程類,該類返回資料,在Thread.Join()方法等待線程結束後寫入資料到表單控制項中,結果和單線程沒有什麼區別;後來查看資料通過使用MethodInvoker解決了這一問題,但是對於線程處理還是概念非常模糊,大家誰有這方面的心得、資料等共用學習學習。    public partial class frmMain : Form
    {
        private volatile bool _stoped = false;

        private void btFilter_Click(object sender, EventArgs e)
        {
            _stoped = false;
            Thread t = new Thread(new ThreadStart(StartNewThread));
            t.Start();
        }

        private void btStop_Click(object sender, EventArgs e)
        {
            _stoped = true;
        }

        private void GetFileSize()
        {
            btFilter.Enabled = false;
            using (AutoCADConnector CAD = new AutoCADConnector())
            {
                foreach (ListViewItem t in lvSource.Items)
                {
                    if (!_stoped)
                    {
                        AutoCAD.AcadDocument doc = CAD.Application.Documents.Open(t.SubItems[2].Text, true, "");

                        double[] p1 = new double[] { 0, 0, 0 };    //右上方座標
                        double[] p2 = new double[] { 0, 0, 0 };    //左下角座標
                        double scale = 0;                                  //縮放比例

                        p1 = (double[])doc.GetVariable("EXTMAX");
                        p2 = (double[])doc.GetVariable("EXTMIN");
                        scale = Convert.ToDouble(doc.GetVariable("DIMSCALE"));

                        double w = Math.Ceiling((p1[0] - p2[0]) / scale);
                        double h = Math.Ceiling((p1[1] - p2[1]) / scale);

                        doc.Close(false, "");

                        t.SubItems[1].Text = string.Format("{0}*{1}  {2}", w, h, scale);
                        //lvSource.Refresh();
                        //Thread.Sleep(100);
                        Application.DoEvents();
                    }
                    else
                        break;
                }
            }
            btFilter.Enabled = true;

        }

        private void StartNewThread()
        {
            MethodInvoker me = new MethodInvoker(this.GetFileSize);
            this.BeginInvoke(me);
        }

    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.