日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

詳解C#中線程傳參,返回值和多線程沖突問題的解決_C#教程

作者:dawn ? 更新時間: 2022-12-27 編程語言

在C#中,開啟一個線程很容易。

Thread Th1= new Thread(func);
Th1.Start();
 
private void func(object Obj)
{
    //處理代碼
}

很多情況下,我們是需要對線程進行傳遞參數的,這個也簡單。

1、線程的單一參數傳遞

        private void button1_Click(object sender, EventArgs e)
        {
            Thread Th1= new Thread(func);
            Th1.Start("CSDN");
            Thread.Sleep(500);
        }
 
        private void func(object Obj)
        {
            string Str = Obj as string;
            textBox1.BeginInvoke(new Action(() =>
            {
                textBox1.Text = $"傳入的參數:{Str}";
            }));
        }

2、線程的多參數傳遞以及返回值

上面的例子是單一的參數,參數要求是對象,使用的時候進行了拆箱,根據上面的例子對于多參數,可以使用中間對象來處理,就是在中間對象中放置參數和獲取處理后的結果。

        private void button1_Click(object sender, EventArgs e)
        {
            FinancialInfo FI=new FinancialInfo();
            FI.PersonName = "CSDN";
            FI.PersonDeposit = 123;
            Thread Th1 = new Thread(FI.ThreadChangeFinanceialInfo);
            Th1.Start();
            Thread.Sleep(500);
            textBox1.Text=FI.PersonName+Environment.NewLine+FI.PersonDeposit.ToString();
        }
 
        private class FinancialInfo
        {
            private string Name=string.Empty;
            private int Deposit=0;
            public string PersonName
            {
                get { return Name; }
                set { Name = value; }
            }
 
            public int PersonDeposit
            {
                get { return Deposit; }
                set { Deposit = value; }
            }
 
            public void ThreadChangeFinanceialInfo() 
            {
                this.Name = this.Name + " | C#";
                this.Deposit = this.Deposit + 100;
            }

3、多線程可能引起的沖突

多線程在處理同一對象時容易引起潛在的沖突,這個顯而易見,例如:

        private void button1_Click(object sender, EventArgs e)
        {
            FinancialInfo FI = new FinancialInfo();
            FI.PersonName = "CSDN";
            FI.PersonDeposit = 123;
            Thread Th1 = new Thread(FI.ThreadAdd);
            Thread Th2 = new Thread(FI.ThreadReduce);
            Th1.Start();
            Th2.Start();
            Thread.Sleep(5000);
            textBox1.Text = textBox1.Text + FI.PersonName +"|"+FI.PersonDeposit.ToString()+Environment.NewLine;
        }
 
        private class FinancialInfo
        {
            private string Name=string.Empty;
            private int Deposit=0;
            public string PersonName
            {
                get { return Name; }
                set { Name = value; }
            }
 
            public int PersonDeposit
            {
                get { return Deposit; }
                set { Deposit = value; }
            }
 
            public void ThreadAdd()
            {
                for (int i = 0; i < 1000000; i++)
                {
                    this.Deposit = this.Deposit + 1;
                }
            }
 
            public void ThreadReduce()
            {
                for (int i = 0; i < 1000000; i++)
                {
                    this.Deposit = this.Deposit - 1;
                }
            }
        }

顯示結果:

按道理, FI.PersonDeposit的值是123,加了1000000,也減了1000000,那么最終的結果應該還是123,為什么會是這樣呢?

這就是多線程在處理同一對象時所產生的沖突了,產生的就是所謂的“臟數據”。

上面的代碼因為等待線程執行完,進行了休眠,可以使用Task來寫更簡單。

            var task1 = new Task(FI.ThreadAdd);
            var task2 = new Task(FI.ThreadReduce);
            task1.Start();
            task2.Start();
 
            Task.WaitAll(task1,task2);

Task是比Thread更加高級的概念,一個Task至少包含一個Thread。

解決上面的沖突就是對可能引起沖突的對象進行加鎖判斷。

完整代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace MultiThread
{
    public partial class Form3 : Form
    {
 
        private static readonly object LockObj=new object();
 
        public Form3()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            FinancialInfo FI = new FinancialInfo();
            FI.PersonName = "CSDN";
            FI.PersonDeposit = 123;
            var task1 = new Task(FI.ThreadAdd);
            var task2 = new Task(FI.ThreadReduce);
            task1.Start();
            task2.Start();
            Task.WaitAll(task1, task2);
            textBox1.Text = textBox1.Text + FI.PersonName +"|"+FI.PersonDeposit.ToString()+Environment.NewLine;
        }
 
 
        private class FinancialInfo
        {
            private string Name=string.Empty;
            private int Deposit=0;
            public string PersonName
            {
                get { return Name; }
                set { Name = value; }
            }
 
            public int PersonDeposit
            {
                get { return Deposit; }
                set { Deposit = value; }
            }
 
            public void ThreadChangeFinanceialInfo() 
            {
                this.Name = this.Name + " | C#";
                this.Deposit = this.Deposit + 100;
            }
 
            public void ThreadAdd()
            {
                for (int i = 0; i < 1000000; i++)
                {
                    lock(LockObj)
                    {
                        this.Deposit = this.Deposit + 1;
                    }                    
                }
            }
 
            public void ThreadReduce()
            {
                for (int i = 0; i < 1000000; i++)
                {
                    lock(LockObj)
                    {
                        this.Deposit = this.Deposit - 1;
                    }                    
                }
            }
        }
    }
}

顯示結果:

上面顯示出了正確的結果,但是會耗時。

原文鏈接:https://blog.csdn.net/dawn0718/article/details/128107337

欄目分類
最近更新