Biểu mẫu tôi đang cố gắng phát triển có một loạt 6 hộp hình ảnh và một mảng gồm 6 hình ảnh chết. Tôi có một nút mà khi nhấp vào cần phải tạo ra 6 chủ đề mà "cuộn" con xúc xắc, hiển thị mỗi hình ảnh cho một thời điểm. Vấn đề tôi gặp phải là tôi cần phải gọi một phương thức trong nút bấm sau khi xúc xắc đã được cuộn. Tôi có thể lấy xúc xắc để cuộn nhưng hộp tin nhắn được hiển thị ngay lập tức. Tôi đã thử một vài cách khác nhau và gặp nhiều lỗi khác nhau. Trong phiên bản không hoạt động bên dưới, chương trình bị treo. Tôi đã kiểm tra một tấn tài nguyên nhưng tôi chỉ không nắm bắt một số khái niệm như Đại biểu và Gọi tất cả những điều tốt. Mọi trợ giúp sẽ tuyệt vời! Đây là chương trình của tôiCác vấn đề với chuỗi chủ đề của tôi
namespace testDice
{
public partial class Form1 : Form
{
private Image[] imgAr;
private PictureBox[] picBoxAr;
private Random r;
private Thread[] tArray;
private ThreadStart tStart;
private delegate void setTheImages();
public Form1()
{
InitializeComponent();
setImageArray();
setPicBoxAr();
}
private void setImageArray()
{
imgAr = new Image[6];
imgAr[0] = testDice.Properties.Resources.die6;
imgAr[1] = testDice.Properties.Resources.die1;
imgAr[2] = testDice.Properties.Resources.die2;
imgAr[3] = testDice.Properties.Resources.die3;
imgAr[4] = testDice.Properties.Resources.die4;
imgAr[5] = testDice.Properties.Resources.die5;
}
private void setPicBoxAr()
{
picBoxAr = new PictureBox[6];
picBoxAr[0] = pictureBox1;
picBoxAr[1] = pictureBox2;
picBoxAr[2] = pictureBox3;
picBoxAr[3] = pictureBox4;
picBoxAr[4] = pictureBox5;
picBoxAr[5] = pictureBox6;
}
private void button1_Click(object sender, EventArgs e)
{
roll();
//wait for threads to finish and update images--doesn't work
for (int n = 0; n < 6; n++)
{
while (tArray[n].IsAlive)
{
for (int i = 0; i < 6; i++)
{
this.picBoxAr[i].Update();
}
}
}
MessageBox.Show("Each die has its own thread");
}
private void roll()
{
this.tStart = new ThreadStart(RunAllDiceThreads);
this.tArray = new Thread[6];
for (int i = 0; i < 6; i++)
{
this.tArray[i] = new Thread(tStart);
this.tArray[i].Start();
}
}
private void RunAllDiceThreads()
{
int n = 0;
while (n < 50)
{
setImg();
Thread.Sleep(50);
n++;
}
for (int i = 0; i < 6; i++)
{
if (tArray[i] != null)
{
tArray[i].Abort();
tArray[i] = null;
}
}
}// end RunAllDiceThreads
private void setImg()
{
r = new Random();
for (int i = 0; i < 6; i++)
{
if (this.picBoxAr[i].InvokeRequired)
{
setTheImages s = new setTheImages(setImg);
// parameter mismatch error here
//this.Invoke(s, new object[] { imgAr[r.Next(6)] });
//Freezes here!!
this.Invoke(s);
}
else
{
this.picBoxAr[i].Image = imgAr[r.Next(6)];
}
}
}//end setImg
}// end class Form1
}//end namespace testDice
1. Toàn bộ chương trình đó trông giống như một vi phạm chủ đề an toàn lớn. 2. Tôi nghĩ bạn không cần chủ đề này. Thay vào đó, hãy sử dụng bộ hẹn giờ và cập nhật tất cả các con xúc xắc khi nó đánh dấu. – svick
nhiệm vụ là sử dụng các chủ đề – Mox
Bạn nên cân nhắc sử dụng TPL. – davenewza