C# winform 多线程异步更新UI
最好能给个例子,不要太复杂,也不要太简单。最好子线程放在单独的类中,方便以后增加其他线程模块。...
最好能给个例子,不要太复杂,也不要太简单。最好子线程放在单独的类中,方便以后增加其他线程模块。
展开
展开全部
首先在窗体上放一个button和一个picturebox
(picturebox visible为false)这个多线程的目的是点击按钮后图片正常的运行,另一线程在睡眠10秒后在执行。
private void button1_Click(object sender, EventArgs e)
{
//开启线程
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.Result));
pictureBox1.Visible = true;
button1.Enabled = false;
thread.Start();
}
private void Result()
{
bool ok = this.Do();
this.BeginInvoke(new System.Threading.ThreadStart(delegate()
{
if (ok) MessageBox.Show("成功", "提示");
else MessageBox.Show("失败", "提示");
pictureBox1.Visible = false;
button1.Enabled = true;
}));
}
private bool Do()
{
System.Threading.Thread.Sleep(10000);
return true;
}
(picturebox visible为false)这个多线程的目的是点击按钮后图片正常的运行,另一线程在睡眠10秒后在执行。
private void button1_Click(object sender, EventArgs e)
{
//开启线程
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.Result));
pictureBox1.Visible = true;
button1.Enabled = false;
thread.Start();
}
private void Result()
{
bool ok = this.Do();
this.BeginInvoke(new System.Threading.ThreadStart(delegate()
{
if (ok) MessageBox.Show("成功", "提示");
else MessageBox.Show("失败", "提示");
pictureBox1.Visible = false;
button1.Enabled = true;
}));
}
private bool Do()
{
System.Threading.Thread.Sleep(10000);
return true;
}
追问
大哥能给个线程类是分开的么?还有如果我要更新4个参数咋办?
追答
private void button1_Click(object sender, EventArgs e)
{
//开启线程
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(this.Result));//设置传参线程
Student student = new Student();
student.Id = 1;
student.Name = "张三";
student.Gender = 1;
student.Birthday = DateTime.Parse("1986-12-12");
object o = student;
pictureBox1.Visible = true;
button1.Enabled = false;
thread.Start(o);
}
private void Result(object o)
{
Student stu = o as Student;
bool ok = this.Do(stu);
this.BeginInvoke(new System.Threading.ThreadStart(delegate()
{
if (ok) MessageBox.Show("成功", "提示");
else MessageBox.Show("失败", "提示");
pictureBox1.Visible = false;
button1.Enabled = true;
}));
}
private bool Do(Student stu)
{
System.Threading.Thread.Sleep(1000);
//执行你更新的方法吧
return true;
}
public class Student
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int gender;
public int Gender
{
get { return gender; }
set { gender = value; }
}
private DateTime birthday;
public DateTime Birthday
{
get { return birthday; }
set { birthday = value; }
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询