目錄
一、問題描述
這段時間在做通過C#順序展示圖片時,出現了問題,界面會卡住不動,直到運行結束纔會顯示最後一張圖片。
其中,form.Show()用於顯示圖片,form.setImgIndex(index)用於更新圖片,
form.Show();
int index = 2;
while (index < 264)
{
Thread.Sleep(100);
form.setImgIndex(index);
index += 1;
}
出現上述問題的原因是,窗口顯示和圖片更新在同一個線程裏,在兩者執行時,會出現阻塞。
二、解決方案
通過多線程的方式進行解決,將窗口顯示和圖片更新分別放到一個子線程裏。
三、完整代碼
public void CallToChildThread()
{
try
{
Console.WriteLine("Child thread starts");
int index = 2;
while (index < 264)
{
Thread.Sleep(100);
form.setImgIndex(index);
index += 1;
}
Console.WriteLine("Child Thread Completed");
}
catch (ThreadAbortException e)
{
Console.WriteLine("Thread Abort Exception");
}
finally
{
Console.WriteLine("Couldn't catch the Thread Exception");
}
}
public void ShowAndUpdate()
{
form.Show();
ThreadStart childref = new ThreadStart(CallToChildThread);
Thread childThread = new Thread(childref);
childThread.Start();
}