在非主线程中运行Cocoa GUI [英] Running a Cocoa GUI in a non-main thread
问题描述
主线程(#1):解析参数,加载插件等。
Gui线程(#?):启动gui,处理事件等。它的gui线程。
Cocoa框架是非线程安全的,规则,GUI必须在主线程上运行。断言用于检查这一点。为了尝试解决这个问题,我自己实现了run方法(代码如下) - http:// cocoawithlove .com / 2009/01 / demystifying-nsapplication-by.html - 指南。但我错过了一些东西。打开一个窗口,但保持空白(完全为白色)。虽然如果我在主线程中调用它的工作完美。
所以基本上我需要弄清楚缺少什么。
- (void)run
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
[self finishLaunching];
shouldKeepRunning = YES;
do
{
[pool release];
pool = [[NSAutoreleasePool alloc] init];
NSEvent * event =
[self
nextEventMatchingMask:NSAnyEventMask
untilDate:[NSDate distantFuture]
inMode:NSDefaultRunLoopMode
dequeue:YES] ;
[self sendEvent:event];
[self updateWindows];
} while(shouldKeepRunning);
[pool release];
}
- (void)terminate:(id)sender
{
shouldKeepRunning = NO;
}
这种方法永远不会工作。即使你修复了当前的问题(窗口不绘图),你会立即遇到另一个模糊,不可能修复的问题,另一个,另一个。 Cocoa期望GUI线程成为主线程,故事结束。
I am having a gui/threading related problem in developing a cocoa user interface. The application is designed like this:
Main Thread (#1): parses arguments, loads plugins, etc.
Gui thread (#?): launches the gui, handles events, etc. Its the gui thread.
The Cocoa framework is non-thread safe, but enforces one rule, the GUI must run on the main thread. A assertion is used to check this. To try to go around this I implemented the run method myself (code below) following this - http://cocoawithlove.com/2009/01/demystifying-nsapplication-by.html - guide. But I am missing something. A window is opened, but stays blank (completely white). Although if I make the call in the main thread it works perfectly.
So basically I need to figure out what's missing.
- (void)run
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self finishLaunching];
shouldKeepRunning = YES;
do
{
[pool release];
pool = [[NSAutoreleasePool alloc] init];
NSEvent *event =
[self
nextEventMatchingMask:NSAnyEventMask
untilDate:[NSDate distantFuture]
inMode:NSDefaultRunLoopMode
dequeue:YES];
[self sendEvent:event];
[self updateWindows];
} while (shouldKeepRunning);
[pool release];
}
- (void)terminate:(id)sender
{
shouldKeepRunning = NO;
}
Don't. This approach will never work. Even if you fix your current problem (the window not drawing) you'll immediately run into another obscure, impossible-to-fix problem, and another, and another. Cocoa expects the GUI thread to be the main thread, end of story.
这篇关于在非主线程中运行Cocoa GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!