多线程编辑问题

这是后台代码:
复制代码
 
1 using System;
2  using System.Collections.Generic;
3  using System.ComponentModel;
4  using System.Data;
5  using System.Drawing;
6  using System.Text;
7 using System.Windows.Forms;
8 using System.Threading;//添加名称空间引用
9
10 namespace ThreadMutex1
11 {
12 publicpartialclass Form1 : Form
13 {
14 public Form1()
15 {
16 InitializeComponent();
17 CheckForIllegalCrossThreadCalls =false;//禁用此异常
18 }
19
20 //创建显示字符的线程对象
21 private Thread thread1 =null;
22 private Thread thread2 =null;
23
24 //显示字符
25 privatevoid ShowChar(char ch)
26 {
27 lock (this)
28 {
29 richTextBox1.Text += ch;
30 }
31 }
32
33 //线程thread1调用的方法(显示字符a)
34 privatevoid thread1Show()
35 {
36 while (true)
37 {
38 ShowChar('a');
39 Thread.Sleep(60);
40 }
41 }
42
43 //线程thread2调用的方法(显示字符A)
44 privatevoid thread2Show()
45 {
46 while (true)
47 {
48 ShowChar('A');
49 Thread.Sleep(30);
50 }
51 }
52
53 //线程初始化,并启动线程
54 privatevoid button1_Click(object sender, EventArgs e)
55 {
56
57 thread1 =new Thread(new ThreadStart(thread1Show));
58 thread2 =new Thread(new ThreadStart(thread2Show));
59 thread1.Start();
60 thread2.Start();
61 button1.Enabled =false;
62 button2.Enabled =true;
63 }
64
65 //终止线程
66 privatevoid button2_Click(object sender, EventArgs e)
67 {
68 thread1.Abort();
69 thread2.Abort();
70 button1.Enabled =true;
71 button2.Enabled =false;
72 }
73
74 //关闭窗体时终止线程(否则,VS调试程序将仍处于运行状态)
75 privatevoid Form1_FormClosing(object sender, FormClosingEventArgs e)
76 {
77 if (thread1 !=null) thread1.Abort();
78 if (thread2 !=null) thread2.Abort();
79 }
80 }
81 }
 
 
前台显示:

 
正常运行:

 
但,当我把排他锁去掉时,在启动线程,文本框的A和a显示就会自动清空。。。不解!
复制代码
posted @   小霖2012  阅读(249)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示