This is the fourth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Preface:

Bloggers in written in c # yesterday when you met a problem, send command is a blogger, need to cycle to send, but should I receive is a 1 second delay, appeared, and then I send command cycle, finally received, only the value of the last two commands, so ask anyone will c # in some big group of thread lock, The reply is that this language is used by very few people, so the blogger read the information for self-study, after learning, want to write out and share with everyone, in addition to thread lock, incidentally mention multithreading, write bad, do not like spray.

Once a day, happy mood

1. Let’s start with our problem

We can see that our loop gets the answer very quickly, but when I’m working on a project I need this loop to wait for me to receive the answer, so we’re going to use some knowledge about thread locks.

 private static object lockObj = new object();// Define a thread lock
        private int num = 0;
        private void Test()
        {
            while (true)
            {
             lock (lockObj)// Lock the code block
                {
                    num++;
                    string name = Thread.CurrentThread.Name;// Get the thread name
                    textBox1.AppendText(name+"Test."+num);// This is the append to TextBox1
                    textBox1.AppendText(System.Environment.NewLine);
                    Thread.Sleep(2000);// Suspend the thread, which is equivalent to stopping for 2 seconds
                   
                    if (num>=10)// Let the thread exit 10 times
                    {
                        break; }}}}Copy the code

While (true) means that the Thread is running until the lock is unlocked. Lock (lockObj) means lock, lock this block of code until unlocked, just keep running, as long as we don’t unlock, the blogger just uses break to exit,Sleep means the thread is suspended, just stop waiting. We can use this to implement a loop function waiting for a reply.

While (true) can define the number of threads according to its instance. In theory, the more threads, the faster, but also consider thread waste.

// thred1 = new Thread(Test); // Define a thread thred1.Name = "thred1"; // Thread name thred1.isBACKGROUND = true; // Set the background thread to True thred1.start (); Int n = thred1.ManagedThreadId; // The thread ID identifies console.writeline (n);Copy the code

We can see from the name, one Thread1 and one Thred2. We can see that the exit condition of the blogger is greater than or equal to 10. Theoretically it should stop at 10, but we used two threads. By the time the second thread arrives, our num is already 10. Thread one has already quits, so thread two quits at 11.

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; namespace IC00 { public partial class Form1 : Form { public Form1() { System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; // Throw textBox1.appendText InitializeComponent(); } private static object lockObj = new object(); Private int num = 0; private void Test() { while (true) { lock (lockObj) { num++; string name = Thread.CurrentThread.Name; Textbox1. AppendText(name+" test :"+num); / / this is the additional TextBox1 TextBox1 AppendText (System. Environment. NewLine); Thread.Sleep(2000); If (num>=10)// let the thread execute 10 times to exit {break; }}}} private void button1_Click(Object sender, EventArgs e) {// Thred1 = new Thread(Test); // Define a thread and run Test thred1.Name = "thred1"; // Thread name thred1.isBACKGROUND = true; // Set the background thread to True thred1.start (); Int n = thred1.ManagedThreadId; // The thread ID identifies console.writeline (n); Thread thred2 = new Thread(Test); thred2.Name = "thred2"; thred2.IsBackground = true; thred2.Start(); int m = thred2.ManagedThreadId; Console.WriteLine(m); // Print thread ID in controller to see if it is a thread}}}Copy the code

Using dual threads can speed up our output, and using multiple threads can speed up our output greatly.

Self-summary:

The problem is that I write you encounter a problem, didn’t know you need to use the thread, and then through the data access, use the thread lock, in fact, I use of is not how well but as long as he is willing to learn, can be learned, person, always unceasing progress, to avoid confusion, there are some things need to rely on yourself. Well, that’s all for today’s sharing. Ha, ha, ha