线程里如何使用控件?

RayLynn 2005-09-21 04:19:34
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ControlAndThread
{
public partial class Form1 : Form
{
private Thread thread;
public Form1()
{
InitializeComponent();
thread = new Thread(new ThreadStart(addItem));
thread.Start();
}

private void addItem()
{
try
{
listBox1.Items.Add("A");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

}
/////////////////////////////////////////////////////////////

错误发生在这行:listBox1.Items.Add("A");
请问为什么这里使用 listBox1 就发生异常,而我假如换成 Console.Writeline("A");就没错了。

这里可能跟线程有关系。等待解释。
第二帖!
...全文
119 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
rcom10002 2005-09-29
  • 打赏
  • 举报
回复
MSDN例子

class Account
{
int balance;

Random r = new Random();

public Account(int initial)
{
balance = initial;
}

int Withdraw(int amount)
{

// This condition will never be true unless the lock statement
// is commented out:
if (balance < 0)
{
throw new Exception("Negative Balance");
}

// Comment out the next line to see the effect of leaving out
// the lock keyword:
lock (this)
{
if (balance >= amount)
{
Console.WriteLine("Balance before Withdrawal : " + balance);
Console.WriteLine("Amount to Withdraw : -" + amount);
balance = balance - amount;
Console.WriteLine("Balance after Withdrawal : " + balance);
return amount;
}
else
{
return 0; // transaction rejected
}
}
}

public void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(1, 100));
}
}
}

class Test
{
public static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account (1000);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
}
}

多个线程都来DoTransactions取钱,但不能没钱也给啊,所以每次只能有一个线程访问acc对象,就是把acc锁住,防止banlance被减成负的了。
RayLynn 2005-09-21
  • 打赏
  • 举报
回复
我不明白为什么要锁定this。

this 是表示当前引用的对象。锁定了有什么意义?
RayLynn 2005-09-21
  • 打赏
  • 举报
回复
请问,这里的 lock(this)

this 是对象吗?

为什么要 lock (this)?
我的理解是,lock块中表示同步快(即:只允许独占式操作)是吗?

那这里为什么要锁定 this ,实在不明白;。
SeeSunSet 2005-09-21
  • 打赏
  • 举报
回复
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace ThreadMutex
{
/// <summary>
/// 多线程互斥实例。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
// Windows 窗体设计器支持所必需的
InitializeComponent();
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
// textBox1
this.textBox1.Dock = System.Windows.Forms.DockStyle.Top;
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(384, 216);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "";
// button1
this.button1.Location = new System.Drawing.Point(104, 232);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "开始";
this.button1.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this.button1.Click += new System.EventHandler(this.button1_Click);
// button2
this.button2.Enabled = false;
this.button2.Location = new System.Drawing.Point(208, 232);
this.button2.Name = "button2";
this.button2.TabIndex = 2;
this.button2.Text = "结束";
this.button2.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this.button2.Click += new System.EventHandler(this.button2_Click);
// Form1
this.AutoScaleBaseSize = new System.Drawing.Size(8, 18);
this.ClientSize = new System.Drawing.Size(384, 264);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.button2,
this.button1,
this.textBox1});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "多线程互斥";
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.ResumeLayout(false);

}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
// 定义两个线程变量。
System.Threading.Thread thdOne;
System.Threading.Thread thdTwo;
// 定义一个线程运行状态变量。
public const int START = 1;
public const int STOP = 2;
public int m_iRun = STOP;
// 输出显示字符。
public void ShowChar(char ch)
{
lock(this)
{
textBox1.Text += ch;
}
}
// 第一个线程。
public void ThreadOne()
{
while(true)
{
System.Threading.Thread.Sleep(50);
ShowChar('A');
}
}
// 第二个线程。
public void ThreadTwo()
{
while(true)
{
System.Threading.Thread.Sleep(25);
ShowChar('B');
}
}
// 开始线程运行。
private void button1_Click(object sender, System.EventArgs e)
{
textBox1.Text = "";
thdOne = new System.Threading.Thread(new System.Threading.ThreadStart(this.ThreadOne));
thdTwo = new System.Threading.Thread(new System.Threading.ThreadStart(this.ThreadTwo));
thdOne.Start();
thdTwo.Start();
button1.Enabled = false;
button2.Enabled = true;
m_iRun = START;
}
// 结束线程运行。
private void button2_Click(object sender, System.EventArgs e)
{
button1.Enabled = true;
button2.Enabled = false;
m_iRun = STOP;
if (thdOne != null)
thdOne.Abort();
if (thdTwo != null)
thdTwo.Abort();
}
// 关闭窗体。
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (m_iRun == START)
{
m_iRun = STOP;
if (thdOne != null)
thdOne.Abort();
if (thdTwo != null)
thdTwo.Abort();
}
}
}
}
SeeSunSet 2005-09-21
  • 打赏
  • 举报
回复
try
{
lock(this){
listBox1.Items.Add("A");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
RayLynn 2005-09-21
  • 打赏
  • 举报
回复
一样有错!!
兄弟。

有没有办法啊!?
急``在线等候```````````````````````
fangwancong 2005-09-21
  • 打赏
  • 举报
回复
和线程没关系的.
thread = new Thread(new ThreadStart(addItem));
thread.Start();
为什么要写在构造函数中?把它放在OnShow事件中吗?

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧