C# 多线程中的函数同步
如果有一个对象 object,里面有两个方法分别是 a() b(), 他们都会修改数据 data;在多线程下,一个线程会调用 a(),一个线程会调用 b()。这样的情况下如何保证数据 data 的安全,这两个函数如何同步呢?
我的想法是这样的,把方法 a() 和 b() 封装到一个函数里面去,再在函数内部进行判断需要执行什么操作,然后对此函数进行线程同步。
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();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了