I want to use NSWorkspace to check if application is launched or closed.
But the process is Launch Daemon and Apple documentation says its not thread safe.
However, the part of code that makes use of Workspace will not be executed at start up or login time. It will be executed after some commands received from other application via BSD communication and process is background process without UI?
Is it safe to use Appkit framework in this situation? Only NSWorkspace API and no other? Alternate solution is Polling? What is your suggestion?
Generally you can use any code that isn't thread safe, as long as you are only doing one operation of whatever the unthreadafe operation is at any given time. I would go ahead and try it, and just be aware that whatever you are doing you can't do concurrently, if you absolutely need to do something concurrently you can try throwing a couple of #synchronized blocks around the code, either in callbacks of a long running background process, or delegate calls.
Related
I'm currently trying to use Rust C interop in order to send actional desktop notifications (using a modified version of this lib). The main goal here would be to handle these notification sending events on separate threads like so:
thread::spawn(move || unsafe {
sys::sendNotification(
NSString::from_str(&title).deref(),
NSString::from_str(&message).deref(),
NSString::from_str(&uri).deref(),
NSString::from_str(&img.unwrap_or_default()).deref(),
);
});
This would allow me to have multiple notification 'handlers' running at the same time (vs. just being able to have a single notification displayed at once), and would also allow my main process to run without being blocked. Given the nature of the program (web-scraper), I don't want scraping halted whenever a notification is being displayed.
That said, this approach is somewhat problematic because the underlying obj-c code relies on NSRunLoop to handle click events (e.g., user clicks on the action to open a web page) through the created NotificationCenterDelegate instance. Per my knowledge (feel free to fact-check me on this I'm not familiar with obj-c), NSRunLoops only operate on the main thread and this code is rendered useless if ran on a worker... The notification still sends in this scenario, but events aren't processed.
Is there a way to handle this that is more effective than running my scraping logic on a separate loop and sending notif-send events to the main thread for processing (which will probably be halted by a notification that I hadn't opened)?
Strictly speaking, there is (or can be) one NSRunLoop per thread, not only the main thread. But it's still the case that GUI stuff generally needs to run on the main thread.
I recommend that you take the approach of running scraping on a separate thread. This is generally a good idea for any combination of long-running work and GUI — it ensures that the work cannot cause the UI to hang or hiccup.
The GUI of my program freezes while the program is doing its work. I created a mass import which can send X-thousand datarows via a called webservice into a database. The code is already very big and I cannot rewrite it for multithreading purpose.
I don't know how to do it. Any suggestions? If needed I will show some code, but at the moment I don't know what to show.
Firstly, you should rewrite it to use avoid synchronously doing this on the UI thread. If you do a lot of work on the UI thread, it simply will freeze the UI thread. There are a few options here:
If your web service proxy supports asynchronous calls, and if you're using VB 11, you can use Async / Await to call the web service asynchronously from the UI thread in an asynchronous method, and control will return back to the UI thread at the same point in the asynchronous method when the call has completed. It takes a little while to get your head round asynchrony, but this is probably the best option if it's possible.
You can use the Task Parallel Library to make calls on a different thread, but then you'll need to think carefully about how that thread is going to interact with your UI thread.
You can use BackgroundWorker to run some code on another thread, but report progress and completion back on the UI thread
You could potentially call Application.DoEvents between each web service call, to let the UI handle events. This is dangerous - it can lead to re-entrant code, so locks won't behave as you expect them to, and similar hard-to-diagnose errors. This should be your last option, if all else fails.
I am building one application on Mac OS X (10.6). In this application, I have one screen where user will provide input and that will be saved as a plist in local folder. This plist file needs to be trasferred to server using HTTP POST service. There should be check for server connectivity and if connections fails the files will be saved in local folder. With certain time duration, again the server connection will be checked and if found, then send all the files store in local folder one by one.
Basically, The GUI application will run continously to get input from user and in another thread there should be check for server connectivity and sending the files.
So my question is what might be the good approach to solve the problem and if any one can send some sample code, it would be great to me.
Thanks,
Barun
There are several approaches to threading in Objective-C! The easiest strategy is NSOperationQueue. Override NSOperation to handle your HTTP request, optionally set a completion block if you need to be notified when it's done, add an instance of it to an NSOperationQueue object and you're good to go. Set up an NSTimer to reschedule the upload if it fails the first time. You can use NSURLConnection to handle the web stuff. Note that NSURLConnection can make connections asynchronously or blocking. Since your NSOperation subclass runs in a separate thread already, you probably want to use the blocking method (if you don't you have to create a concurrent NSOperation subclass, which is a lot more work).
You can also use Grand Central Dispatch's API, detach a new thread to methods you specify, or use plain old c (I wouldn't recommend the last two but it's good to mention them). As a bonus, NSOperationQueue and Grand Central Dispatch both know "what's right" when you have multiple operations running at once, and will scale the number of threads to fit the number of core's in the user's computer to obtain the best performance.
Check the docs for NSOperationQueue, NSOperation, and NSURLConnection. The guides and example projects will have all the source code you need to get you started in the right direction.
I was wondering if there was a way that I could get notifications of when a system process from /usr/sbin starts and finishes. Is it possible to attach NSTask to the running process without launching a new one? Preferably without polling please :!
For UI process you can use NSRunningApplication. You can observe the "terminated" property to know when it finishes. You can listen to NSWorkspaceWillLaunchApplicationNotification to know when an application will be launched.
Since you're not running a UI application the above probably won't work. You'll have to use more low level BSD calls. Here's an example of how you can know when an process terminates:
https://developer.apple.com/library/content/technotes/tn2050/_index.html#//apple_ref/doc/uid/DTS10003081-CH1-SUBSECTION10
Good luck!
Scenario:
I have a Distributed-objects-based IPC between a mac application and a launchd daemon (written with Foundation classes). Since I had issues before regarding asynchronous messaging (e.g. I have a registerClient: on the server's root object and whenever there's an event the server's root object notifies / calls a method in the client's proxy object), I did long-polling which meant that the client "harvests" lists of events / notifications from the daemon. This "harvest" is done through a server object method call, which then returns an NSArray instance.
It works pretty well, until for a few seconds, the server object's process (launched thru launchd) starts being labeled red with the "(Not responding)" tag beside it (inside Activity Monitor). Like I said, functionally, it works well, but we just want to get rid of this "Not responding" label.
How can I prevent this "Not responding" tag?
FYI, I already did launchd-based processes before and this is the first time I did long-polling. Also, I tried NSSocketPortNameServer-based connections and also NSSocketPort-based ones. They didn't have this problem. Locking wasn't also an issue 'coz the locks used were only NSCondition's and we logged and debugged the program and it seems like the only locking "issue" is on the harvesting part, which actually, functionally works. Also, client-process is written in PyObjC while server process was written using ObjC.
Thanks in advance.
Sample the process to find out what it's doing or waiting on.
Peter's correct in the approach, though you may be able to figure it out through simple inspection. "Not responding" means that you're not processing events on your event queue for at least 5 seconds (used to be 2 seconds, but they upped it in 10.4). For a UI process, this would create a spinning wait cursor, but for a non-UI process, you're not seeing the effects as easily.
If this is a runloop-based program, it means you're probably doing something with a blocking (synchronous) operation that should be done with the run loop and a callback (async). Alternately, you need a second thread to process your blocking operations so your mainthread can continue to respond to events.
My problem was actually the call for getting a process's PID using the signature FNDR... that part caused the "Not responding" error and it never was the locks or the long-polling part. Sorry about this guys. But thank God I already found the answer.