在一个C#项目上工作,我想以一个单独的形式实现一个“等待”(throbber)指示符。经过大量的研究、尝试和错误之后,似乎建议这样做的方法是使用与当前表单/线程不同的线程加载表单。
我之所以使用这个方法,是因为最初在throbber表单上使用Show()方法会产生一个透明的表单。我不能使用ShowDialog,因为我需要在显示throbber之后运行一些代码,在此之后,我想关闭throbber表单。
总之..。在尝试了许多不同的方法将throbber表单加载到一个单独的线程中之后,我仍然会遇到一个错误,即尝试从一个不同于在线程中创建的线程访问它。下面是一个skelton版本的项目代码,应该能说明我的问题:
我正在处理的多线程示例是一个流行的链接,用于在一个单独的线程中创建您自己的闪存. http://www.codeproject.com/Articles/5454/A-Pretty-Good-Splash-Screen-in-C
public class Main
{
public void CheckData()
{
try
{
ProgressBar pb = new ProgressBar();
pb.ShowProgressBar();
//do data checking here
pb.CloseForm()
}
catch(Exception e)
{
}
}
}
public partial class ProgressBar : Form
{
static Thread ms_oThread = null;
public bool shouldStop = false;
static ProgressBar ms_ProgBar = null;
public ProgressBar()
{
InitializeComponent();
//DoWork();
}
public void ShowForm()
{
ms_ProgBar = new ProgressBar();
Application.Run(ms_ProgBar);
}
public void CloseForm()
{
ms_ProgBar.Close();
}
public void ShowProgressBar()
{
// Make sure it is only launched once.
if (ms_ProgBar != null)
return;
ms_oThread = new Thread(new ThreadStart(ShowForm));
ms_oThread.IsBackground = true;
ms_oThread.SetApartmentState(ApartmentState.STA);
ms_oThread.Start();
while (ms_ProgBar == null || ms_ProgBar.IsHandleCreated == false)
{
System.Threading.Thread.Sleep(1000);
}
}
}发布于 2014-05-08 16:19:40
您要创建两次ProgressBar。一次在您的主要功能,一次在您的新线程。您还将从主函数(以及从未显示的窗口)调用CloseWindow方法,而不是在新线程窗口上调用。
您只想创建ProgressBar并使用新线程显示它。让静态ProgressBar字段公开,这样您就可以直接从Main调用它,但是要确保使用Invoke来完成它,因为它不在该窗口的GUI线程上。
另外,ShowProgressBar应该是静态的。
下面是一次重写尝试:
public class Main
{
public void CheckData()
{
try
{
ProgressBar.ShowProgressBar();
//do data checking here
ProgressBar.CloseForm();
}
catch(Exception e)
{
}
}
}
public partial class ProgressBar : Form
{
static ProgressBar _progressBarInstance;
public ProgressBar()
{
InitializeComponent();
//DoWork();
}
static void ShowForm()
{
_progressBarInstance = new ProgressBar();
Application.Run(ms_ProgressBar);
}
public static void CloseForm()
{
_progressBarInstance.Invoke(new Action(_progressBarInstance.Close));
_progressBarInstance= null;
}
public static void ShowProgressBar()
{
// Make sure it is only launched once.
if (_progressBarInstance != null)
return;
var ms_oThread = new Thread(new ThreadStart(ShowForm));
ms_oThread.IsBackground = true;
ms_oThread.SetApartmentState(ApartmentState.STA);
ms_oThread.Start();
}
}https://stackoverflow.com/questions/23546722
复制相似问题