请教一个简单问题(多线程的)
先说一下我的问题:主要就是想实现(winform中)
1.在时钟里更新数组,
2.在一个线程中利用这个数组的值画出曲线。
下面是我写的程序,图就画了一次不知道怎么回事?请高手指教。。。。
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 WindowsApplication3
{
public partial class Form1 : Form
{
static int[] a = new int[10];
static int[] b = new int[10];
static int count = 0;
Object obj = new Object();//
public Form1()
{
InitializeComponent();
}
private void draw()
{
Graphics g = pictureBox1.CreateGraphics();
Pen pen1 = new Pen(Color.Red, 2);
g.Clear(Color.White);
lock (a)
{
for (int i = 0; i < 9; i++)
g.DrawLine(pen1, a[i], b[i], a[i + 1], b[i + 1]);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
lock (a)
{
for (int i = 0; i < 10; i++)
{
a[i] = (50 + count * 10) * i;
if (i % 2 == 0) b[i] = 30;
else b[i] = 50;
}
if (count < 10) count++;
else count = 0;
}
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
a[i] = 50 * i;
if (i % 2 == 0)b[i] = 30;
else b[i] = 50;
}
}
private void button1_Click(object sender, EventArgs e)
{
ThreadStart ts = new ThreadStart(draw);
Thread thread = new Thread(ts);
thread.Start();
timer1.Enabled = true;
}
}
}
[解决办法]
哦,你是要线程间隔自动执行?那就把调用线程放在时钟里面就可以了。
private void timer1_Tick(object sender, EventArgs e)
{
lock (a)
{
for (int i = 0; i < 10; i++)
{
a[i] = (50 + count * 10) * i;
if (i % 2 == 0) b[i] = 30;
else b[i] = 50;
}
if (count < 10) count++;
else count = 0;
button1_Click(null,null);
}
[解决办法]
要看效果就这样,但这觉不是什么合理的设计
private void draw(){ Pen pen1 = new Pen(Color.Red, 2); while (true) { Graphics g = pictureBox1.CreateGraphics(); g.Clear(Color.White); lock (a) { for (int i = 0; i < 9; i++) g.DrawLine(pen1, a[i], b[i], a[i + 1], b[i + 1]); } g.Dispose(); Thread.Sleep(100); }}
[解决办法]
1.lock 关键字哪儿修改一下 lock(obj)
2.再用一个timer 专门负责取数组值更新绘图 你使用thread.start 无法满足你提供的需求一个线程修改一个线程绘图(不间断的) 因为start只会执行一次
多线程数据块共享 关键还是在于怎么使用锁机制