gpt4 book ai didi

c# - Windows 窗体 - 如何启动单独的线程并保持当前线程

转载 作者:行者123 更新时间:2023-12-02 15:03:03 25 4
gpt4 key购买 nike

我有一个Windows应用程序和一个DLL(Windows窗体),我试图打开(ActivationCheck),我试图暂停当前线程打开一个新线程(ActivationCheck)等待该窗体事件返回true然后继续主线程。有人可以解释\告诉我我做错了什么 - 谢谢。

 static class Program
{
private static SplashScreen splash;
private static bool quitApp;
private static bool activationFinished;

[STAThread]
static void Main()
{

Thread thread = new Thread(ActivationCheck);
thread.Start();



do
{
Thread.Sleep(1000);
} while (activationFinished);

if (!quitApp)
{


Thread.Sleep(0);
// WizardRun();
Application.Run(new Main(ref splash));
}
}
}

private static void ActivationCheck()
{

splash.SetStatus = "Checking License...";

Guid productId = new Guid(Properties.Settings.Default.ProductId);
Guid versionId = new Guid(Properties.Settings.Default.VersionId);

Client.UI.EntryPoint entryPoint = new EntryPoint();

activationFinished = false;

Client.BLL.ProductActivation.GenerateTrialLicense(productId1, versionId2, EditionId3);
entryPoint.IniatePlugin(productId, versionId);
entryPoint.PluginFinished += new EventHandlers.PluginFinishEventHandler(entryPoint_PluginFinished);


}
static void entryPoint_PluginFinished(bool forceQuit)
{
quitApp = forceQuit;
activationFinished = true;


}

最佳答案

你可以直接执行thread.Join()吗?但说实话,我不太确定启动第二个线程并暂停第一个线程的意义是什么;只在原来的线程上做工作?

代码的问题可能是activationFinished被保存在寄存器中;尝试将其标记为 volatile ,或者在访问此变量的两个位置使用。更好的是使用 ManualResetEvent 或类似的,并从激活代码中打开它。

using System;
using System.Threading;
static class Program
{
static void Main()
{
new Thread(DoActivation).Start();
Console.WriteLine("Main: waiting for activation");
activation.WaitOne();
Console.WriteLine("Main: and off we go...");
}
static void DoActivation(object state)
{
Console.WriteLine("DoActivation: activating...");
Thread.Sleep(2000); // pretend this takes a while
Console.WriteLine("DoActivation: activated");
activation.Set();
// any other stuff on this thread...
}
static ManualResetEvent activation = new ManualResetEvent(false);
}

关于c# - Windows 窗体 - 如何启动单独的线程并保持当前线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2122672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com