In c #, you can call this method directly to solve the thread access control problem,

Source: Internet
Author: User

In c #, you can call this method directly to solve the thread access control problem,
Problem

When c # is a beginner, a thread delegate is used to execute functions to prevent the software form from being suspended. Use the following code:

Thread th = new Thread (Getform); // create a Thread
Th. Start ();

Before use, you need to introduce: using System. Threading;

 

However, in the Getform function, I call the command to modify the content of the Form Control.

Textbox. text = "false ";

An error is reported.

The Inter-thread operation is invalid: It is accessed by a thread that is not creating the control "textbox ".

Okay. Find the information and view the solution,

Solution:

1. Directly ignore the thread permission check.

Public Form1 ()
{
InitializeComponent ();
Control. checkforillegalcrossthreadcils = false;
}

We have added this code: Control. checkforillegalcrossthreadcils = false; // ignore the thread permission check.

My personal understanding: This directly ignores other problems, so we do not recommend them, but it can be used in some cases. After all, it is convenient...

2. Use the delegate for security modification, and use delegate and invoke to control information from other threads (Network replication instructions)

The Code on the network is copied directly to C # For more obvious display.

Public partial class Form1: Form {private delegate void FlushClient (); // proxy public Form1 () {InitializeComponent ();} private void Form1_Load (object sender, EventArgs e) {Thread thread = new Thread (CrossThreadFlush); thread. isBackground = true; thread. start ();} private void CrossThreadFlush () {// bind the proxy to the method FlushClient fc = new FlushClient (ThreadFuntion); this. beginInvoke (fc); // call proxy} private void ThreadFuntion () {while (true) {this. textBox1.Text = DateTime. now. toString (); Thread. sleep (1000 );}}}

It seems relatively simple, but this will make the window no response, because in the infinite refresh window,. Will there be better solutions.

The final solution:

private void button1_Click(object sender, EventArgs e)        {            var th = new Thread(() =>            {                //label1.Enabled = false;                label1.CrossThreadCalls(() => { label1.Enabled = !label1.Enabled; });                WriteMessage(DateTime.Now.ToString());            });            th.IsBackground = true;            th.Start();        }        public void WriteMessage(string msg)        {            label1.CrossThreadCalls(() =>            {                label1.Text = msg;            });        }

Before use, we create a class.

Using System. threading; using System. windows. forms; namespace WindowsFormsApplication1 {public static class Class1 {// <summary> // cross-thread access control to execute delegation on the control /// </summary> // <param name = "ctl"> Control </param> // <param name = "del"> delegate executed </param> public static void crossthreadcils (this Control ctl, threadStart del) {if (del = null) return; if (ctl. invokeRequired) ctl. invoke (del, null); else del ();}}}

  

Finally, we come up with this solution. Not bad.

 

I just recorded it during the learning process. You are welcome to discuss it.

 

Address: http://www.lazyw.org/weituo.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.