如果有一个对象 object,里面有两个方法分别是 a() b(), 他们都会修改数据 data;在多线程下,一个线程会调用 a(),一个线程会调用 b()。这样的情况下如何保证数据 data 的安全,这两个函数如何同步呢?

我的想法是这样的,把方法 a() 和 b() 封装到一个函数里面去,再在函数内部进行判断需要执行什么操作,然后对此函数进行线程同步。

C# 多线程中的函数同步_C#

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.Forms;

namespace CsTest
{
internal enum HahaOrHello
{
Haha,
Hello
}


public partial class FormMain : Form
{
private int _count = 0;
private Mutex _mutex = new Mutex();

private string _message = null;

public FormMain()
{
InitializeComponent();
}

private void ShowMessage()
{
if (listBox1.InvokeRequired)
{
listBox1.Invoke(new Action(() =>
{
if (listBox1.Items.Count > 20)
{
listBox1.Items.RemoveAt(20);
}

listBox1.Items.Insert(0, _count.ToString() + " " + _message);

_count++;

}));
}
else
{
if (listBox1.Items.Count > 20)
{
listBox1.Items.RemoveAt(20);
}

listBox1.Items.Insert(0, _count.ToString() + " " + _message);

_count++;
}
}

private void SayHaha()
{
_message = "哈哈~哈哈~";
}

private void SayHelloWorld()
{
_message = "Hello World!!";
}

private void Do(HahaOrHello hahaOrHello)
{
_mutex.WaitOne();

if (hahaOrHello == HahaOrHello.Haha)
{
SayHaha();
}
else if (hahaOrHello == HahaOrHello.Hello)
{
SayHelloWorld();
}

ShowMessage();

_mutex.ReleaseMutex();
}


private Thread _th1 = null;
private Thread _th2 = null;

private void FormMain_Load(object sender, EventArgs e)
{
_th1 = new Thread(new ThreadStart(() =>
{
while (true)
{
Do(HahaOrHello.Haha);
Thread.Sleep(500);
}
}));

_th2 = new Thread(new ThreadStart(() =>
{
while (true)
{
Do(HahaOrHello.Hello);
Thread.Sleep(500);
}
}));

_th1.IsBackground = true;
_th2.IsBackground = true;

_th1.Start();
_th2.Start();
}
}
}