带有守护进程的 C# 托盘图标应用程序
这里是完全的 C# 新手,所以请放宽我的要求。
我有一个将位于托盘上的应用程序。当我单击托盘时,我想访问“设置”表单。这一切都已编码并且可以工作。
然而,这个应用程序的主要功能是连接到用 node.js 编写的应用程序并不断轮询要做的事情。
这也是编码和工作的,但是有一个(可怕的)警告。
主类这样做:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form = new Form1();
ApplicationContext applicationContext = new ApplicationContext();
applicationContext.MainForm = form;
Application.Run(applicationContext);
}
}
为了以隐藏的形式运行。主应用程序周期以 Load 事件的形式发生:
private void Form1_Load(object sender, EventArgs e)
{
string basePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Personal),
"ArchSync"
);
if (!Directory.Exists(basePath)) {
Directory.CreateDirectory(basePath);
}
WebClient client = new WebClient();
Int64 timestamp = 0;
while (true)
{
// main app loop
}
}
不用说,该应用程序可以工作,但托盘图标没有执行任何操作,因为主线程正忙于进行 HTTP 交互。
在 UI 线程之外执行主应用程序循环的正确方法是什么?
谢谢!
Complete C# newbie here, so cut me some slack.
I have this application that will live on the tray. When I click the tray I want to access a "settings" form. This is all coded and working.
However, the main feature of this app is to connect to an application written in node.js and keep polling for things to do.
This is also coded and working, however there is a (horrible) caveat.
The main class does this:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form = new Form1();
ApplicationContext applicationContext = new ApplicationContext();
applicationContext.MainForm = form;
Application.Run(applicationContext);
}
}
In order to run with the form hidden. And the main app cycle is taking place in the form Load event:
private void Form1_Load(object sender, EventArgs e)
{
string basePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Personal),
"ArchSync"
);
if (!Directory.Exists(basePath)) {
Directory.CreateDirectory(basePath);
}
WebClient client = new WebClient();
Int64 timestamp = 0;
while (true)
{
// main app loop
}
}
Needless to say, this application works but the tray icon does nothing, since the main Thread is busy doing HTTP interactions.
What is the correct way to execute the main application loop outside the UI thread?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
System.Threading
命名空间中的Thread.Start
。但是,如果您想从工作线程更新 UI,最简单的方法是使用System.ComponentModel
命名空间中的BackgroudWorker
。You can use
Thread.Start
from theSystem.Threading
namespace. But if you want to update UI from the worker thread, these easiest way to do it, is to use aBackgroudWorker
from theSystem.ComponentModel
namespace.