我将以下C#代码编译到一个名为“最小表单应用程序.dll“
using System;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsTest
{
public static class CreateACoolWindow
{
public static void Main(string[] args)
{
CreateWindow();
}
public static void CreateWindow()
{
Thread winFormsThread = new Thread(new ThreadStart(StartFormApplication));
winFormsThread.SetApartmentState(ApartmentState.STA);
winFormsThread.Start();
Console.WriteLine("Started thread");
}
private static void StartFormApplication()
{
Application.EnableVisualStyles();
Console.WriteLine("EnableVisualStyles");
Application.SetCompatibleTextRenderingDefault(false);
Console.WriteLine("SetCompatibleTextRenderingDefault");
FormSubClass dmw = new FormSubClass();
Console.WriteLine("Created window object");
Application.Run(dmw);
}
}
public class FormSubClass : Form
{
public FormSubClass()
{
Console.WriteLine("FormSubClass Constructor called");
InitializeComponent();
}
private void InitializeComponent()
{
Console.WriteLine("Starting component init......");
this.SuspendLayout();
this.AutoScaleDimensions = new SizeF(6F, 13F);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(300, 500);
this.Name = "FormSubClass";
this.Text = "FormSubClass";
this.ResumeLayout(false);
this.PerformLayout();
}
}
}
将Python for.NET与python2.7 for x86一起使用,我尝试从这个C#库调用CreateWindow()方法。在
我的python代码如下:
^{pr2}$这是Python在控制台上输出的内容
Started thread
Mary had a little lamb,EnableVisualStyles
SetCompatibleTextRenderingDefaultit's fleece was white as snow;
and everywhere that Mary went her lamb was sure to go.
FormSubClass Constructor called
可以看出,它不打印“Starting component init……”,也不打印“Created window object”,实际上也没有创建任何窗口。Python程序结束并不会产生错误消息,说明为什么没有创建窗口。在
如果我从另一个C程序调用同一个C库,则所有内容都将按预期打印,并创建窗口。在
有人知道为什么Python for.NET在Forms constructor上失败了吗?
当Python中的主线程终止时,它也会终止在.NET中运行的所有内容。在
在上面给出的示例中,在将文本打印到terminal之后,在主Python线程终止之前,窗口还没有时间绘制。在
在新的python线程中启动.NET调用将阻止此操作。在
在找另一个问题的时候偶然发现了这个问题。 我来晚了一点,但我想我可以为任何有类似问题的人提供一个解释。在
当CPython解释器跟踪线程时,它将它们放入 三类。在
Normal用于通过线程模块启动的常规python线程。当这些线程或主线程正在运行时,解释器将不会退出。在
类似地,守护程序线程是通过线程模块启动的线程;但是,它们已被标记为守护程序。在这种情况下,解释器在退出之前不会等待它们终止。在
最后,外来线程是在与CPython相同的进程中启动的线程,但不是由任何python代码启动的。解释器知道这些,但不知道如何等待它们,因此将它们视为守护进程线程,而不是等待它们在退出之前终止。在
为了更好地处理windows上的线程(加上没有GIL),请查看IronPython。它可能比较慢,但它只是更好地处理这样的.NET交互,因为它是作为本机.NET运行的。在
相关问题 更多 >
编程相关推荐