Chào mừng đến với Diễn đàn lập trình - Cộng đồng lập trình.
Kết quả 1 đến 10 của 10
  1. #1
    Ngày tham gia
    Sep 2015
    Bài viết
    0

    Cross-thread operation not valid

    Mình đang làm một chương trình kiểm tra đường truyền (ping) giống cái cmd/ping của win, mình đã tham khảo chương trình này http://www.java2s.com/Code/CSharp/Network/AdvancedPingProgram.htm và mình có chạy thử trên vs2003 thì chạy ngon lành cành đào, nhưng mình làm trên vs2008 thì bị lỗi Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on. Mình đã xem bài của bạn sunflower ở bài http://diendan.congdongcviet.com/threads/t5794::xu-ly-loi-cross-thread-cross-thread-operation-not-valid.cpp và đã sửa thành công nhưng đến lúc chạy thì ô listbox ko hiện lên kết quả. Chú ý phần tớ làm trên vs2008 phải chờ lâu lâu 1 tý nhé.

    File ping là file tớ làm trên vs2008 còn file ping_test là tớ thử trên 2003.

  2. #2
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Mình cũng đang research về vấn đề thay đổi giá trị dynamic trên control. Bạn có thể dựa vào demo bên dưới để sửa lại ví dụ của bạn. Nếu có thắc mắc về việc áp dụng demo này qua ví dụ của bạn thì post lên đây để cùng thảo luận.
    Form 1:
    Mã:
    delegate void ShowProgressDelegate(int totalMessages, int messagesSoFar, bool statusDone);
            private void button2_Click(object sender, EventArgs e)
            {
                ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);
                int imsgs = 100; 
                WorkerClass wc = new WorkerClass(this, showProgress, new object[] { imsgs });
                Thread t = new Thread(new ThreadStart(wc.RunProcess));
                t.IsBackground = true; //make them a daemon - prevent thread callback issues
                t.Start();
            }
    private void ShowProgress(int totalMessages, int messagesSoFar, bool done)
            {
                this.dataGridView1.Rows.Add(messagesSoFar.ToString());
                this.dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Selected = true;
                dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount - 1;
            }
    Class WorkerClass:
    Mã:
    /// <summary>
    	/// Summary description for WorkerClass.
    	/// </summary>
    	public class WorkerClass
    	{
    		/// <summary>
    		/// Usually a form or a winform control that implements "Invoke/BeginInvode"
    		/// </summary>
    		ContainerControl m_sender = null;
    
    		/// <summary>
    		/// Messages sent in - this is implementation specific
    		/// </summary>
    		int m_totalMessages = 0;
    
    		/// <summary>
    		/// The delegate method (callback) on the sender to call
    		/// </summary>
    		Delegate m_senderDelegate = null;
    
    		/// <summary>
    		/// Constructor used by caller using ThreadPool
    		/// </summary>
    		public WorkerClass()
    		{
    		}
    		/// <summary>
    		/// Constructor called by calle using ThreadPool OR ThreadStart
    		/// </summary>
    		/// <param name="sender"></param>
    		/// <param name="totalMessages"></param>
    		/// <param name="sp"></param>
    		public WorkerClass ( ContainerControl sender, Delegate senderDelegate, int totalMessages)
    		{
    			m_sender = sender;
    			m_senderDelegate = senderDelegate;
    			m_totalMessages = totalMessages;
    		}
    
    		/// <summary>
    		/// Another constructor using the params array pattern. Used by ThreadPool or ThreadStart
    		/// </summary>
    		/// <param name="sender"></param>
    		/// <param name="senderDelegate"></param>
    		/// <param name="list"></param>
    		public WorkerClass ( ContainerControl sender, Delegate senderDelegate, params object[] list)
    		{
    			m_sender = sender;
    			m_senderDelegate = senderDelegate;
    			m_totalMessages = (int) list.GetValue(0);
    		}
    
    		/// <summary>
    		/// Method for ThreadStart delegate
    		/// </summary>
    		public void RunProcess()
    		{
    			Thread.CurrentThread.IsBackground = true; //make them a daemon
    			LocalRunProcess();
    		}
    
    		/// <summary>
    		/// Local Method for the actual work.
    		/// </summary>
    		private void LocalRunProcess()
    		{
    			int i = 0;
    			for ( ; i < m_totalMessages; i++)
    			{
    				Thread.Sleep(50);
    				m_sender.BeginInvoke( m_senderDelegate, new object[] { m_totalMessages, i, false } );
    			}
    			m_sender.BeginInvoke( m_senderDelegate, new object[] { m_totalMessages, i, true } );
    		}

  3. #3
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    bạn có thể gửi code dể mình chạy thử đc ko ? Mình dùng vs2008 nhé.

  4. #4
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Code đó rồi bạn. Tạo thêm 1 Button và 1 datagridview nữa là run được thôi.

  5. #5
    Ngày tham gia
    Dec 2015
    Bài viết
    0
    The type or namespace name 'ContainerControl' could not be found (are you missing a using directive or an assembly reference?)

    mình thử và nó báo bị lỗi này bạn ơi, bên class ý

    - - - Nội dung đã được cập nhật ngày 31-03-2015 lúc 11:23 PM - - -

    Exception has been thrown by the target of an invocation

    mình sửa đc rồi nhưng giờ lại thành lỗi này, bạn gửi code mình chạy luôn cho nhanh.

  6. #6
    Đây bạn, dựa vào rồi edit lại cho project của bạn thôi

  7. #7
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Trích dẫn Gửi bởi hoangthi
    Bạn thêm 1 class sau:
    Mã:
    public static class ThreadHelperClass
            {
                delegate void SetTextCallback(Form f, ListBox ctrl, string text);
                public static void AddText(Form form, ListBox ctrl, string text)
                {
                    if (ctrl.InvokeRequired)
                    {
                        SetTextCallback d = new SetTextCallback(AddText);
                        form.Invoke(d, new object[] { form, ctrl, text });
                    }
                    else
                    {
                        ctrl.Items.Add(text);
                    }
                }
            }
    Tại dòng
    Mã:
    lbKetqua.Items.Add("Ping to " + txtPing.Text + "[" + r.Address.ToString() + "]" + " Successful"
                       //+ " Response delay = " + r.RoundtripTime.ToString() + " ms" + "
    ");
    Bạn sửa thành
    Mã:
    string sdfs = "Ping to " + txtPing.Text + "[" + r.Address.ToString() + "]" + " Successful"
                       + " Response delay = " + r.RoundtripTime.ToString() + " ms" + "
    ";
                        ThreadHelperClass.AddText(this,lbKetqua,sdfs);
    Tại dòng
    Mã:
    lbKetqua.Items.Add("Request time out");
    Bạn sửa thành
    Mã:
    ThreadHelperClass.AddText(this, lbKetqua, "Request time out");
    Enjoy
    Mình thử nhưng không được bạn ạ, nó không đưa ra từng dòng một được, code chuẩn là phần code AdvPing đó bạn, mình thử thì nó chạy hoàn chỉnh trên vs2003 nhưng trên vs2008 thì bị lỗi Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on. Mình đã sửa thành công lỗi này nhưng khi chạy thì ô listbox lại không hiện một cái gì lên, mặc dù chương trình vẫn chạy, chờ một lúc lâu thì bạn sẽ thấy thanh cuôn xuất hiến đó bạn. Đó thực ra chỉ là bước đầu trong chương trình của mình thôi, chương trình mình làm mục đích nó sẽ thực hiện ping trên nhiều địa chỉ mà mình sẽ chọn trong ô checklistbox và chỉ ping trong một khoảng thời gian do mình ấn định, đồng thời quá trình ping sẽ là quá trình ghi ra file txt nữa. Tức là vừa hiện trên ô listbox vừa lưu vào file text. Đó là chương trình mình đang hướng tới.

    P/s: cám ơn bạn hvcuongit, mình sẽ nghiên cứu và thử

  8. #8
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Trích dẫn Gửi bởi nobita611
    Mình đang làm một chương trình kiểm tra đường truyền (ping) giống cái cmd/ping của win, mình đã tham khảo chương trình này http://www.java2s.com/Code/CSharp/Network/AdvancedPingProgram.htm và mình có chạy thử trên vs2003 thì chạy ngon lành cành đào, nhưng mình làm trên vs2008 thì bị lỗi Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on. Mình đã xem bài của bạn sunflower ở bài http://diendan.congdongcviet.com/threads/t5794::xu-ly-loi-cross-thread-cross-thread-operation-not-valid.cpp và đã sửa thành công nhưng đến lúc chạy thì ô listbox ko hiện lên kết quả. Chú ý phần tớ làm trên vs2008 phải chờ lâu lâu 1 tý nhé.

    File ping là file tớ làm trên vs2008 còn file ping_test là tớ thử trên 2003.
    Bạn thêm 1 class sau:
    Mã:
    public static class ThreadHelperClass
            {
                delegate void SetTextCallback(Form f, ListBox ctrl, string text);
                public static void AddText(Form form, ListBox ctrl, string text)
                {
                    if (ctrl.InvokeRequired)
                    {
                        SetTextCallback d = new SetTextCallback(AddText);
                        form.Invoke(d, new object[] { form, ctrl, text });
                    }
                    else
                    {
                        ctrl.Items.Add(text);
                    }
                }
            }
    Tại dòng
    Mã:
    lbKetqua.Items.Add("Ping to " + txtPing.Text + "[" + r.Address.ToString() + "]" + " Successful"
                       //+ " Response delay = " + r.RoundtripTime.ToString() + " ms" + "
    ");
    Bạn sửa thành
    Mã:
    string sdfs = "Ping to " + txtPing.Text + "[" + r.Address.ToString() + "]" + " Successful"
                       + " Response delay = " + r.RoundtripTime.ToString() + " ms" + "
    ";
                        ThreadHelperClass.AddText(this,lbKetqua,sdfs);
    Tại dòng
    Mã:
    lbKetqua.Items.Add("Request time out");
    Bạn sửa thành
    Mã:
    ThreadHelperClass.AddText(this, lbKetqua, "Request time out");
    Enjoy

  9. #9
    Đã edit lại project theo yêu câu của bạn, mình chỉ sửa lại code để chạy cho đúng kết quả thôi, bạn tối ưu lại nó nhé.

  10. #10
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    ko chạy đc bạn ơi, mình dùng vs2008, cậu dùng vs2015 ah.

 

 

Quyền viết bài

  • Bạn Không thể gửi Chủ đề mới
  • Bạn Không thể Gửi trả lời
  • Bạn Không thể Gửi file đính kèm
  • Bạn Không thể Sửa bài viết của mình
  •