这是我的代码,但label1在label2之前先运行?我想要的是在各自的线程上同时运行label1和label2。我一直使用线程,但它不能访问控件,除了它自己创建的线程。所以在这段代码中,当我创建实例如:Slave s1 = new Slave(label1); Slave s2 = new Slave(label2);
时,它会自动开始移动这两个标签,但不是。
public class Slave
{
private Label l;
private BackgroundWorker bw;
public Slave(Label l)
{
this.l = l;
bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.DoWork+=new DoWorkEventHandler(worknow);
bw.ProgressChanged += new ProgressChangedEventHandler(update);
bw.RunWorkerAsync();
}
private void worknow(object sender, DoWorkEventArgs e)
{
BackgroundWorker b = sender as BackgroundWorker;
b.ReportProgress(1);
}
private void update(object sender, ProgressChangedEventArgs e)
{
for(int x=0; x<20;x++)
{
l.Top += 10;
System.Threading.Thread.Sleep(100);
}
}
}
答案 0 :(得分:0)
好的,我刚刚找到了问题的解决方案,所以我会回答我自己的问题,所以我有一个winform,1个面板和一个按钮这么简单,所以我有一个Animate类,Animate a = new Animate( PANEL1,startingX,startingY,下一页末,newY);实例化将在起始位置创建一个节点,并在每按一个按钮一次将其移动到所需的新位置,类节点的定义如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class Node:Label
{
public Node(int x, int y)
{
this.Top = y;
this.Left = x;
}
public void updatePos(int x, int y)
{
this.Top += y;
this.Left += x;
}
}
}
然后这是animate类的定义:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Animate a = new Animate(panel1,0,0,1,1); //this is the actual instatiation test
Animate b = new Animate(panel1, 100, 0,2,2); //for node b
}
public class Animate
{
private Node l;
Thread th;
private delegate void cl(int x, int y);
Delegate del;
private int a, b;
public Animate(Panel p, int x, int y, int a, int b)
{
l = new Node(0,0);
del = new cl(l.updatePos);
this.a = a;
this.b = b;
this.l.AutoSize = true;
this.l.Location = new System.Drawing.Point(x, y);
this.l.Name = "label1";
this.l.Size = new System.Drawing.Size(35, 13);
this.l.TabIndex = 0;
this.l.Text = "label1";
p.Controls.Add(l);
th = new Thread(thread);
th.Start();
}
private void thread()
{
while (true)
{
try
{
l.Invoke(del, a, b);
Thread.Sleep(100);
}
catch (Exception e)
{
return;
}
}
}
}
}
}
有些人可能想知道我需要什么,我正在尝试使用纯粹的C#编码winform应用程序来实现二进制搜索树和AVL模拟器,这就是为什么我称标签为“节点”