хочу написать универсальный (более или менее для моих целей) класс-форму типа "Please wait...".
Все там вроде работает только почему то если быстро быстро нажимать кнопочку запускащую поток а потом поток закрывающий то выдает ошибку что поток был прерван пока он был в ожидании:
Вот собственно класс:
public partial class WaitForm : Form
{
string _messageText = String.Empty;
bool _showOK = false;
bool _showCancel = false;
Thread _thread = null;
public WaitForm(Thread thread, string messageText)
{
InitForm(thread, messageText, false, false);
}
public WaitForm(Thread thread, string messageText, bool showOK)
{
InitForm(thread, messageText, showOK, false);
}
public WaitForm(Thread thread, string messageText, bool showOK, bool showCancel)
{
InitForm(thread, messageText, showOK, showCancel);
}
private void InitForm(Thread thread, string messageText, bool showOK, bool showCancel)
{
InitializeComponent();
_messageText = messageText;
_showOK = showOK;
_showCancel = showCancel;
_thread = thread;
labelMessage.Text = _messageText;
buttonOK.Visible = _showOK;
buttonCancel.Visible = _showCancel;
buttonOK.Enabled = false;
buttonCancel.Enabled = true;
}
public void StopThread(string messageText)
{
_messageText = messageText;
StopThread();
}
public void StopThread()
{
if (InvokeRequired)
Invoke(new MethodInvoker(delegate()
{
pictureBoxWaiter.Visible = false;
labelMessage.Text = _messageText;
if (!ShowOK)
this.DialogResult = DialogResult.OK;
buttonOK.Enabled = true;
buttonCancel.Enabled = false;
}));
else
{
pictureBoxWaiter.Visible = false;
labelMessage.Text = _messageText;
if (!ShowOK)
this.DialogResult = DialogResult.OK;
buttonOK.Enabled = true;
buttonCancel.Enabled = false;
}
//_thread.Interrupt(); // -------- не всегда упсевает завершить поток, и процесс грузится
_thread.Abort();
}
private void buttonOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
//_thread.Interrupt();
_thread.Abort();
this.DialogResult = DialogResult.Cancel;
this.Close();
}
}
а вот так я его использую
Thread backgroundThread = null;
WaitForm wait = null;
private void button1_Click(object sender, EventArgs e)
{
backgroundThread =
new Thread(new ThreadStart(Initialization));
wait = new WaitForm(backgroundThread, "Пожалуйста ждите, идет инициализация", true, true);
backgroundThread.Start();
DialogResult result = wait.ShowDialog();
//backgroundThread.Interrupt();
}
public void Initialization()
{
for (long i = 0; i < 200000000; i++)
{
long s = 234;
s = s * s * s * s * s * s * s;
}
wait.StopThread("Операция завершена успешно");
}
Вопрос соственно в том, корректно ли испльзовать Thread.Abort()? Я почему то слышал что правильней пользоваться Interrupt(), однако он не убивает поток, он его доделывает а потом только завершает. Может быть это изза того как я его подгрушаю
Данное сообщение получено с сайта GotDotNet.RU
|