문제

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!

도움이 되었습니까?

해결책

You can use Thread.Start from the System.Threading namespace. But if you want to update UI from the worker thread, these easiest way to do it, is to use a BackgroudWorker from the System.ComponentModel namespace.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top