我有两个C# winform (.NET 4.0)表单,每个表单都可以连续运行不同但相似的自动化任务。因为它们是截然不同的流程/工作流,但在操作方式上足够相似,以便在项目中共享相同的资源(方法、数据模型、程序集等)。
这两个表单都已完成,但现在我不确定如何运行该程序,以便每个窗口在启动时打开并独立运行。该程序在部署时将是“始终在线”的。
这可能看起来有点基础,但我的大部分开发经验都是web应用程序。线程/etc对我来说还是有点陌生。我已经研究过了,但我发现的大多数答案都与用户交互和顺序用例有关--这将只是一个系统连续运行两个不同的进程,需要独立地与世界交互。
我发现的潜在解决方案可能涉及多线程,或者可能是某种MDI,或者一些人建议使用DockPanelSuite (尽管在超级企业环境中,下载第三方文件说起来容易做起来难)。
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Rather than specifying frmOne or frmTwo,
// load both winforms and keep them running.
Application.Run(new frmOne());
}
}
发布于 2013-03-09 02:45:31
您可以创建一个新的ApplicationContext
来表示多个表单:
public class MultiFormContext : ApplicationContext
{
private int openForms;
public MultiFormContext(params Form[] forms)
{
openForms = forms.Length;
foreach (var form in forms)
{
form.FormClosed += (s, args) =>
{
//When we have closed the last of the "starting" forms,
//end the program.
if (Interlocked.Decrement(ref openForms) == 0)
ExitThread();
};
form.Show();
}
}
}
使用它,你现在可以写:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MultiFormContext(new Form1(), new Form2()));
发布于 2013-03-09 02:44:38
如果你真的需要两个窗口/窗体在两个单独的UI线程上运行,你可以这样做:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var thread = new Thread(ThreadStart);
// allow UI with ApartmentState.STA though [STAThread] above should give that to you
thread.TrySetApartmentState(ApartmentState.STA);
thread.Start();
Application.Run(new frmOne());
}
private static void ThreadStart()
{
Application.Run(new frmTwo()); // <-- other form started on its own UI thread
}
}
https://stackoverflow.com/questions/15300887
复制相似问题