跨平台线程和GTK#,不能正常工作吗? [英] Crossplatform threading and GTK#, not working (properly)?

查看:57
本文介绍了跨平台线程和GTK#,不能正常工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#,Linux上的mono / GTK#和Windows上的.NET / GTK#创建一个跨平台的C#应用​​程序,但是在两个平台下启动顺序似乎需要稍有不同:

I'm trying to make a crossplatform C# application using C#, mono/GTK# on Linux and .NET/GTK# on Windows, however the startup sequence seems to need to be slightly different under the two platforms:

在Linux下:

public static void Main (string[] args)
{
    Gdk.Threads.Init ();
    // etc...

在Windows下:

public static void Main (string[] args)
{
    Glib.Thread.Init ();
    Gdk.Threads.Init ();
    // etc...

两者都要求这样做:Windows抱怨关于g_thread_init()没有被linux代码调用的问题,linux抱怨它已经被Windows代码调用。

Both require it to be done that way: Windows complains about g_thread_init() not being called with the linux code, and linux complains about it already being called with the Windows code. Other than this, it all works wonderfully.

我第一次尝试解决方案的过程如下:

My first attempt at a "solution" looked like:

public static void Main (string[] args)
{
    try {
        Gdk.Threads.Init ();
    } catch (Exception) {
        GLib.Thread.Init ();
        Gdk.Threads.Init ();
    }
    // etc...

但是即使这个凌乱的解决方案也不能不工作;该错误来自GTK +,非托管代码,因此无法捕获。是否有人对问题的原因以及解决方法有什么聪明的主意?否则,是否有关于如何在运行时检测应该调用哪个方法的好主意?

But even this messy solution doesn't work; the error is coming from GTK+, unmanaged code, so it can't be caught. Does anyone have any bright ideas about the cause of the problem, and how to fix it? Or, failing that, have bright ideas on how to detect which one should be called at runtime?

推荐答案

Win32上的Gtk +不会正确支持线程。您需要从与调用Gtk.Main()相同的线程进行所有GUI调用。

Gtk+ on Win32 does not properly support threading. You need to do all your GUI calls from the same thread as you did called Gtk.Main().

实际上并没有听起来那么糟糕。您可以使用一个技巧将函数分派到主线程。只需在任何线程中使用GLib.Idle.Add(),函数就会在与运行主循环相同的线程中不久被调用。只需记住在空闲处理函数中返回false,否则它将永远运行。

It's not actually as bad as it sounds. There's a trick you can use to dispatch functions to the main thread. Just use GLib.Idle.Add() from any thread and the function will be called shortly in the same thread as the main loop is running in. Just remember to return false in the idle handler function, or it will go on running forever.

如果您遵循并使用上述技术,甚至根本不需要调用Gdk.Threads.Init()。

If you follow and use the above techniques you don't even need to call Gdk.Threads.Init() at all.

这篇关于跨平台线程和GTK#,不能正常工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆