0

I've tried implementing some code to launch a thread and perform an operation after it joins. The only problem is that it never returns from the thread. Can anyone tell me what I'm doing wrong?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Prototype
{
    public partial class Form1 : Form
    {

        public static string Decrypt(string cipherData, string keyString)
        {
            // decrypt stuff
        }

        public List<String[]> loadDB()
        {
            // load db
        }

        public List<String[]> StartForm()
        {
            List<String[]> data = loadDB();
            Application.Run(new Splash());
            return data;
        }

        public Form1()
        {
            List<String[]> data = null;
            Thread t = new Thread(() => { data = StartForm(); });
            t.Start();
            Thread.Sleep(5000);
            Debug.WriteLine("There");
            Debug.WriteLine(t.ThreadState.ToString());
            t.Join();
            Debug.WriteLine("Here" + data[0][0]);
            InitializeComponent();
            label1.Text = data[0][0];
        }
    }
}

I was expecting "Here" + datum to output.

Ken White
  • 123,280
  • 14
  • 225
  • 444

1 Answers1

1

Looking at your code, the fundamental issue is that the Application.Run(Form) method is a blocking call intended to run the message loop of the main form specifically. The Microsoft documentation for Application.Run(Form) explains:

Begins running a standard application message loop on the current thread, and makes the specified form visible. [...] Every running Windows-based application requires an active message loop, called the main message loop. When the main message loop is closed, the application exits.

So, it should only be used in Program.cs to invoke the main form.


Reading your code, the intent seems to be to spawn a separate thread to display a splash screen. This "separate thread" approach may in itself may be inadvisable since the splash has its own message loop that needs to run on the UI thread. The short answer to cannot get past Thread.Join is don't put yourself in the position of having to use it in the first place.

To understand various ways to approach displaying a splash screen refer to this answer and other posts on the same thread.

IVSoftware
  • 5,732
  • 2
  • 12
  • 23