I created a splashscreen its working but it didnt solve what i needed i had how can i load the constructor while the splahshscreen is loading?

后端 未结 1 1509
挽巷
挽巷 2021-01-29 07:16

In the top of form1 i did:

InitializeComponent();

            Thread t = new Thread(new ThreadStart(SplashScreen));
            t.Start();
            Thread.Sl         


        
1条回答
  •  走了就别回头了
    2021-01-29 07:55

    You're creating a new thread to handle the UI of your splash screen so that your first UI thread can continue on to do some other non-UI based processing.

    Don't do that.

    Multiple UI threads are a really bad idea. They're very hard to work with, result in buggy code, don't play well with framework code, etc. Just don't do it unless you really know what you're doing, and even then, avoid it at all costs.

    Instead, do the non-UI work in a non-UI thread, and do all of your UI work, for the entire application, in a single UI thread.

    The other issue is that we'll want are splash screen to be shown before our main form is shown, so to handle that we'll move to the program.cs file to alter how the entire application is started.

    First we'll create the splash screen and the object to handle the long running work, then start that long running work in another thread, and instruct it to close the splash screen when it's done. (Note that we're closing the form nicely here, rather than using Abort. Abort is something else to avoid at all possible costs.)

    Then we just show the splash screen in the main thread, and when it has been closed, we show the main form. We also pass in the results of the long running process to the main form, so you'll need to create a property for it to be able to have those results passed into. We'll also be able to leverage the cancellation capabilities of the Task Parallel Library to ensure that the splash screen is closed after 5 seconds, even if the task isn't completed at that point:

    SplashScreen splash = new SplashScreen();
    Computer computer = new Computer();
    Task.Factory.ContinueWhenAny(new[]{
        Task.Factory.StartNew(() => computer.Open()),
        Delay(TimeSpan.FromSeconds(5))
    },
    t => splash.Close());
    
    Application.Run(splash);
    Application.Run(new MainForm() { Computer = computer });
    

    And here's a Delay implementation, since you're using 4.0 and don't have access to the one added in 4.5:

    public static Task Delay(TimeSpan timeout)
    {
        var tcs = new TaskCompletionSource();
        new System.Threading.Timer(_ => tcs.TrySetResult(true),
            null, (long)timeout.TotalMilliseconds, Timeout.Infinite);
        return tcs.Task;
    }
    

    0 讨论(0)
提交回复
热议问题