我有一个应用程序,我写了一些繁重的任务,我在其中显示一个任务表单。此任务表单显示当前进度,以及在繁重任务线程中设置的状态文本。我现在遇到的问题是,在表单实际显示自己的时间之前调用My Invoke调用(UpdateStatus方法),并开始抛出异常。
这是我的表格:
public partial class TaskForm : Form
{
const int WM_SYSCOMMAND = 0x0112;
const int SC_MOVE = 0xF010;
/// <summary>
/// The task dialog's instance
/// </summary>
private static TaskForm Instance;
/// <summary>
/// Private constructor... Use the Show() method rather
/// </summary>
private TaskForm()
{
InitializeComponent();
}
public static void Show(Form Parent, string WindowTitle, string InstructionText, string SubMessage, bool Cancelable, ProgressBarStyle Style, int ProgressBarSteps)
{
// Make sure we dont have an already active form
if (Instance != null && !Instance.IsDisposed)
throw new Exception("Task Form is already being displayed!");
// Create new instance
Instance = new TaskForm();
// === Instance form is setup here === //
// Setup progress bar...
// Hide Instruction panel if Instruction Text is empty...
// Hide Cancel Button if we cant cancel....
// Set window position to center parent
// Run form in a new thread
Thread thread = new Thread(new ThreadStart(ShowForm));
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Thread.Sleep(500); // Wait for Run to work or the Invoke exceptions are thrown
}
public static void CloseForm()
{
// No exception here
if (Instance == null || Instance.IsDisposed)
return;
try
{
Instance.Invoke((Action)delegate()
{
Instance.Close();
Application.ExitThread();
});
}
catch { }
}
protected static void ShowForm()
{
Application.Run(Instance);
}
public static void UpdateStatus(string Message)
{
if (Instance == null || Instance.IsDisposed)
throw new Exception("Invalid Operation. Please use the Show method before calling any operational methods");
Instance.Invoke((Action)delegate()
{
Instance.labelContent.Text = Message;
});
}
new public void Show()
{
base.Show();
}
}
注意:我确实删除了一些与我的问题无关的代码
问题在于此示例:
//显示任务对话框
TaskForm.Show(this, "My Window Title", "Header Text", false);
TaskForm.UpdateStatus("Status Message"); // Exception Thrown HERE!!
如果没有ShowForm()方法中的Thread.Sleep(),我会得到可怕的Invoke异常(InvalidOperationException =&gt;&#34;在创建窗口句柄之前,无法在控件上调用Invoke或BeginInvoke。 #34)。有没有更好的方法来显示此表单以防止这些问题?我感到内疚,不得不使用Thread.Sleep()来等待GUI像它所支持的那样弹出。
答案 0 :(得分:1)
您可以使用IsHandleCreated
属性[msdn]来确定是否已创建窗口句柄。所以不需要sleep
时间,我们不能保证不变。
所以你可以使用像
这样的东西TaskForm.Show(this, "My Window Title", "Header Text", false);
while(!this.IsHandleCreated); // Loop till handle created
TaskForm.UpdateStatus("Status Message");
我已经使用了它并且它对我有用,我也欢迎任何有关此解决方案的评论。