Send message between processes - c#

I'm creating an application with background audio player. According to MS requirements, the player is implemented as a separate DLL and lives in another process.
I'm able to pass track name back to my UI process by updating a BackgroundAudioPlayer.Instance.Track object.
However I'd like my UI to also report state of my download buffer.
What IPC method can I use on WP7 to notify my GUI process?
Update: I considered using 4 named manual reset events to pass 4 bits of the data - fail, WP7 only supports unnamed events that are only suitable for thread synchronization within the same process.
I considered System.Windows.Messaging - fail, SendCompletedCallback raises "LocalMessage_CouldNotDeliverMessage", and the documentation says local messaging is not supported on WP7.
So far, I know only one way - write files to isolated storage, and guard them with named mutex. I don't really want to wear out the NAND flash by doing that. Are there better methods? WP7 has WinCE kernel underneath, which has plenty methods available - mailslots, LPC, RPC, COM, pipes, shared memory, and many others - I can't believe none of them is exposed to SilverlightÂ…

Related

C# Restricting DLL's to only one instance

I essentially want to make an api for an application but I only want one instance of that dll to be running at one time.
So multiple applications also need to be able to use the DLL at the same time. As you would expect from a normal api.
However I want it to be the same instance of the dll that the different applications use. This is because of communication with hardware that I don't want to be able to overlap.
DLLs are usually loaded once per process, so if your application is guaranteed to only be running in single-instance mode, there's nothing else you have to do. Your single application instance will have only one loaded DLL.
Now, if you want to "share" a "single instance" of a DLL across applications, you will inevitably have to resort to a client-server architecture. Your DLL will have to be wrapped in a Windows Service, which would expose an HTTP (or WCF) API.
You can't do that as you intend to do. The best way to do this would be having a single process (a DLL is not a process) which receives and processes messages, and have your multiple clients use an API (this would be your DLL) that just sends messages to this process.
The intercommunication of those two processes (your single process and the clients sending or receiving the messages via your API) could be done in many ways, choose the one that suits you better (basically, any kind of client/server architecture, even if the clients and the server are running on the same hardware)
This is an XY-Problem type of question. Your actual requirement is serializing interactions with the underlying hardware, so they do not overlap. Perhaps this is what you should explicitly and specifically be asking about.
Your proposed solution is to have a DLL that is kind of an OS-wide singleton or something like that. This is actually what you are asking about; although it is still not the right approach, in my opinion. The OS is in charge of managing the lifetime of the DLL modules in each process. There are many aspects to this, but for one: most DLL instances are already being shared between every process (mostly code sections, resources and such - data, of course, is not shared by default).
To solve your actual problem, you would have to resort to multi-process synchronization techniques. In Windows, this works mostly through named kernel objects like mutexes, semaphores, events and such. Another approach would be to use IPC, as other folks have already mentioned in their respective answers, which then again would require in itself some kind of synchronization.
Maybe all this is already handled by that hardware's device driver. What would be the real scenarios in which overlapped interactions with the underlying hardware would have a negative impact on the applications that use your DLL?
To ensure you have loaded one DLL per machine, you would need to run a controlling assembly in separate AppDomain, then try creating named pipe for remoting (with IpcChannel) and claim hardware resources. IpcChannel will fail to create second time in the same environment. If you need high performance communication with your hardware, use remoting only for claiming and releasing resource by another assembly used by applications.
Mutex is one of solution for exclusive control of multiple processes.
***But Mutex will sometimes occur dead lock. Be careful if you use.

In which cases using language with GC allows audio playback without dropouts?

As far as I know, using a language with Garbage Collection means there will be time intervals, inside which entire application is stopped. But I'm curious about the scope of this stops.
For example, there are PortAudio bindings for Java, and there are 2 modes of operation, which differ in control direction. In one mode you call PortAudio to put some data that it must play and in other mode PortAudio calls you (callback function) to fill its buffers with data. I am wondering, why Java bindings for PortAudio don't allow second mode (using callback). The explanation is, as can be read here: This Java binding does not support audio callbacks because an audio callback should never block. Calling into a Java virtual machine might block for garbage collection or synchronization. So only the blocking read/write mode is supported. This implies that in other case GC should not be a problem? But why? I don't understand this.
And how the situation will differ in other programming languages with GC? (especially interesting are C# and D.) What things should I take care of if I want to implement an audio player (that never ever drops out samples) in language with GC while using only 1 process? And is it possible at all?
Previously I was participating in developing a kind of VoIP software in Java and there was serious problems with dropouts which correlated in time with GCs. But doing music player should be easier, I think, because latency is not a problem here and I can use huge buffer for audio data.
Update:
I am interested only in free and open source solutions. So, for example, using an "alternative" but non-free implementation of Java runtime is not an option for me to use. But it's interesting to know anyway.

C# Eventing across IPC

Ok, long story short I have a Windows service that handles Win32_VolumeChangeEvent and logs USB disk device arrivals to the Event Log and to a SQL database. An additional component to this is a hidden UI (WinForms) which loads in the user session at login - this pops up a message box reminding users of company policy about USB keys etc. AFAIK, this was the best way to go since services can no longer run in interactive mode.
Anywho... architecturally, v1 of this little thing ran with the UI component handling WndProc messages for device insertion, then passed the device identifier through IPC (named pipes) to the service which would handle WMI methods / EventLog writing (as not all users have local admin rights). This had the downside of the UI element being process killed and no longer detecting device insertions.
So, current version is that the service handles Win32_VolumeChangeEvents and gets the needed details from the device, then logs to EventLog and SQL. All is outstanding and works perfectly. Except now I'm wondering what the best way to trigger the UI into displaying the popup is.
I've researched around Google and here, looking for ideas about eventing over IPC, so I can just subscribe to an event from the UI component and fire it within the service, but I'm not finding much that jumps out as being helpful. I'm also constrained to .net2, so WCF is out of the picture (although I'm not afraid of p/invoke if you want to go that way).
So. How would you do it? Links, thoughts, ramblings, pseudocode, actual code... all is appreciated. I'm trying to stick to what I believe is best practice, although I also think programming is a bit of an art form and my best practice may be someone else's horror story.
So SO - what would you do? Let me know if I need to clarify :)
Back in the bad old days of Windows API programming, we'd sometimes use RegisterWindowMessage to register a unique message ID that (presumably) only our window knew how to handle. We could then trigger that window from another application by calling PostMessage with a window handle of HWND_BROADCAST, and the msg parameter being that unique message value. That works great if everything you want to share between the processes can fit into two DWORD values (wparam and lparam). Sharing more data can be done if you allocate global memory and pass a reference as one of the parameters.
That should still be possible with .NET. Certainly there's no trouble calling PostMessage. As for handling the message in the UI code, you have to override the Form's WndProc. See How do I send/receive windows messages between VB6 and c#? for an example.
You could do something with named events, although that would only notify the UI that some change had occurred. It wouldn't actually tell you what happened. I suppose, if there's only a small set of possible events, you could have multiple events, but that gets complicated pretty quickly.
You could go the named event route and use shared memory (memory mapped file) to share the state.
Or, you could set up sockets, named pipes, TcpListener/TcpClient, or even a UdpClient. All should work, with varying degrees of complexity and/or reliability.
The only idea that comes to my mind is to have a service check the state of the UI application periodically and restart it if it has been killed. There seems to be no standard module that would run within user's session and let the service send notifications to this module. There exist third-party solutions but they can be killed (not saying that they should be installed in order to be used).
Update: after re-reading the question I think that maybe your UI doesn't receive windows messages, so you need another mechanism. Why not create a Semaphore synchronization object in service and wait for it in UI process (in a separate thread)?

C# - How to implement Pause/Resume semantics?

In an application I'm creating, I've got two components that I want the user to be able to pause/resume. I'm wondering what standard patterns might exist to support pausing and resuming, if any? Both components do a lot of network I/O. It seems like, at a high level, I have to persist the current queue of work that each component has - but persisting it is where I'm looking for these standard patterns? Do I serialize the component itself? Do I serialize just the work? What format do I serialize to (xml, database, etc...)? What does .NET have built in that might help? Are there any libraries to help with this? Are there any differences to consider if the user just pauses/resumes within the same app session or if they pause/resume after opening, closing and then opening the application again? What about persisting this information across different computers?
Any suggestions from past experience or patterns that come to mind? I hope this turns into more of discussion of the various ways of doing this and the pros/cons of each. Thanks.
By message queue I meant MSMQ or one of it's brethren. All messages would be persisted in some sort of database and therefore still available when the app restarts. The primary purpose of such queues is to ensure that messages get delivered even when communication is intermittent and/or unreliable.
It sounds like you could have your communication components take work from MSMQ instead of your current queues pretty easily.
If that doesn't fit your application, it is probably as simple as serializing the objects in your existing queues on termination, and de-serializing them again at application start up. If surviving unexpected termination is important you should always serialize an object as it is added to the work queue, but at that point you may want to look again at an existing message queue system.
You could implement threading and simply call the Suspend() and the Resume() functions on the thread accordingly.

C# communication between processes

I'm working with an application, and I am able to make C# scripts to run in this environment. I can import DLLs of any kind into this environment. My problem is that I'd like to enable communication between these scripts. As the environment is controlled and I have no access to the source code of the application, I'm at a loss as to how to do this.
Things I've tried:
File I/O: Just writing the messages that I would like each to read in .txt files and having the other read it. Problem is that I need this scripts to run quite quickly and that took up too much time.
nServiceBus: I tried this, but I just couldn't get it to work in the environment that I'm dealing with. I'm not saying it can't be done, just that I can't get it done.
Does anyone know of a simple way to do this, that is also pretty fast?
Your method of interprocess communication should depend on how important it is that each message get processed.
For instance, if process A tells process B to, say, send an email to your IT staff saying that a server is down, it's pretty important.
If however you're streaming audio, individual messages (packets) aren't critical to the performance of the app, and can be dropped.
If the former, you should consider using persistent storage such as a database to store messages, and let each process poll the database to retrieve its own messages. In this way, if a process is terminated or loses communication with the other processes temporarily, it will be able to retrieve whatever messages it has missed when it starts up again.
The answer is simple;
Since you can import any DLL into the script you may create a custom DLL that will implement communication between the processes in any way you desire: shared memory, named pipe, TCP/UDP.
You could use a form of Interprocess Communication, even within the same process. Treat your scripts as separate processes, and communicate that way.
Named pipes could be a good option in this situation. They are very fast, and fairly easy to use in .NET 3.5.
Alternatively, if the scripts are loaded into a single AppDomain, you could use a static class or singleton as a communication service. However, if the scripts get loaded in isolation, this may not be possible.
Well, not knowing the details of your environment, there is not much I can really offer. You are using the term "C# scripts"...I am not exactly sure what that means, as C# is generally a compiled language.
If you are using normal C#, have you looked into WCF with Named Pipes? If your assemblies are running on the same physical machine, you should be able to easily and quickly create some WCF services hosted with the Named Pipe binding. Named pipes provide a simple, efficient, and quick message transfer mechanism in a local context. WCF itself is pretty easy to use, and is a native component of the .NET framework.
Since you already have the File I/O in place you might get enough speed by placing it on a RAM disk. If you are polling for changes today a FileSystemWatcher could help to get your communication more responsive.
You can use PipeStream. Which are fast than disk IO as they are done using main memory.
XMPP/Jabber is another appraoch take a look at jabber.net.
Another easy way is to open a TCP Socket on a predefined Port, connect to it from the other process and communicate that way.

Categories

Resources