I'm working on a instant messaging program in C#(for learning only).
Just wanna to know if my way is right or wrong.
I created a Client class whice contains a NetworkStream and Read/Write functions.
The server creates a new thread for every client, the thread listen for any new messages.
Any better way?
You don't necessarily need to spawn a thread for each client. I'd investigate the Observer design pattern as it addresses the publish-subscribe problem, which is a good way to look at an instant messaging application, particularly if you want multiple listeners to one talker.
Here's a good place to start: http://www.blackwasp.co.uk/Observer.aspx. This link discusses the Observer pattern and mentions instant messaging: http://www.oodesign.com/observer-pattern.html.
You may find that a single-threaded approach may be able to keep up with a lot of messages. Depending upon how you design you classes you may find it useful to put entire conversations in their own thread. You should also think about using queues to handle incoming and outgoing messages, with queue readers in their own thread as well.
Sounds like a fun project.
Try WCF. Here is a nice sample.
Related
So we've been looking into the Azure Service Bus recently and we're a bit confused as to whether we should use an infinite loop to poll the queue/subscription or whether we should use the OnMessage callback/message pump functionality. What is going to execute fewer operations and thus cost less?
Ideally we want an event-driven system so we aren't wasting operations and it's just generally a much nicer approach.
My question is, is using OnMessage which is defined as "Processes a message in an event-driven message pump" really event-driven?
If you take a look at this page (QueueClient.OnMessage): https://msdn.microsoft.com/library/azure/microsoft.servicebus.messaging.queueclient.onmessage.aspx you'll notice the remark at the bottom which states that it is basically a wrapper around an infinite loop which is calling the Receive() method. That doesn't sound very event-driven to me.
Now if you look at this page (SubscriptionClient.OnMessage):
https://msdn.microsoft.com/en-us/library/azure/dn130336.aspx, that remark is not present. So is it the same for topics/subscriptions and queues or is it actually event-driven for subscriptions but not for queues?
Why are they even saying it's event-driven when it's clearly not? The fact that the remark on the QueueClient.OnMessage page has the words "infinite loop" and "every receive operation is a billable event" is somewhat scary.
Also, I'm not really concerned about how much/little it will cost either way, I'm more interested in making it as efficient as possible.
I've not used OnMessage, but the question interested me so I did some digging.
My understanding is that the OnMessage approach just encapsulates away some of the usual concerns to do with processing messages from a queue to give you a cleaner/easier way to do it with a lot less to be concerned about. So instead of writing all the scaffolding around polling, you can focus more on a "push-like/event driven" implementation (message pump model).
And so you are correct in that it is basically still just a loop calling Receive() - so with the default timeouts, the number of polls would be the same and therefore same cost.
I came across these references:
http://fabriccontroller.net/introducing-the-event-driven-message-programming-model-for-the-windows-azure-service-bus/
http://www.flyersoft.net/?p=971 - check the comments too, as this covers the same question as yours.
So is it the same for topics/subscriptions and queues or is it
actually event-driven for subscriptions but not for queues?
I am not 100%, but my assumption based on my research is that it is the same and it's just a case that the documentation is not clear.
I'm looking for less technical and more conceptual answers on this one.
I am looking to build a WPF application using .NET 4.5 for controlling a rover, (glorified RC Car). Here is the intended functionality:
The application and rover will communicate wirelessly by sending and receiving strings - JSON over TCP Socket.
The GUI will display multiple video feeds via RTSP.
A control panel - custom hardware - will connect to the computer via USB and these signals will be converted to JSON before being sent over the TCP connection and providing movement instructions.
The GUI will need to update to reflect the state of the control panel as well as the state of the rover based on data received.
I'm not sure which technologies to use to implement this, but from my research, BackgroundWorkers or Threads, and Asynchronous techniques would be things to look into. Which of these seems like a good route to take? Also, should I use TCP Sockets directly in the application or should/could I use WCF to provide this data?
Any wisdom on this would be great. Thanks in advance.
EDIT:
Here was the final implementation used and boy did it workout great:
Everything fell into place around using the MVVM pattern.
There were Views for the control panel and the networking component which each had a corresponding ViewModel that handled the background operations.
Updating the UI was done via databinding, not the Dispatcher.
Wireless Communication was done Asynchronously (async/await) via TCPListener along with the use of Tasks.
Serial Port Communication was done Asynchronously via SerialPort and Tasks.
Used ModernUI for interface.
Used JSON.NET for the JSON parsing.
Here is a link to the project. It was done over the course of a month so it isn't the prettiest code. I have refined my practices a lot this summer so I'm excited to work on a refactored version that should be completed next year.
As you are using .NET 4.5 you dont need to use Threads and background workers for your project. you dont need to take care of all of your threads. As WPF's Dispatcher is a very powerful tool for handling UI from other threads.
For TCP Communication i would suggest you to use TCP Client and TCP Listner with Async Callbacks. and use Dispatcher for Updating your UI.
For Displaying Cameras over RTSP, Use VLC.Net an Open source wrapper for VLC library good for handling many real time video protocols.
Use Tasks instead of Threads, set their priority according to your requirement.
You don't need WCF for your application.
As far as I can tell (I'm no expert), MS's philosophy these days is to use asynchronous I/O, thread pool tasks for lengthy compute operations, and have a single main thread of execution for the main part of the application. That main thread drives the GUI and commissions the async I/O and thread pool tasks as and when required.
So for your application that would mean receiving messages asynchronously, and initiating a task on the thread pool to process the message, and finally displaying the results on the GUI when the task completes. It will end up looking like a single threaded event loop application. The async I/O and thread pool tasks do in fact use threads, its just they're hidden from you in an as convenient a way as possible.
I've tried (once) bucking this philosophy with my own separate thread handling all my I/O and an internal pipe connection to my main thread to tell it what's happening. I made it work, but it was really, really hard work. For example, I found it impossible to cancel a blocking network or pipe I/O operation in advance of its timeout (any thoughts from anyone out there more familiar with Win32 and .NET?). I was only trying to do that because there's no true equivalent to select() in Windows; the one that is there doesn't work with anything other than sockets... In case anyone is wondering 'why of why oh why?', I was re-implmenting an application originally written for Unix and naively didn't want to change the architecture.
Next time (if there is one) I'll stick to MS's approach.
I am developping a client library for a network application protocol.
Client code calls the library to init it and to connect to server.
The client can of course send requests to the server, but the server can also send requests (Commands, called Cmd below) to the client.
The transport protocol is TCP/IP, so basically the client library connect to the server and make a call to an async method to retrieve the next request or response from the server in order to avoid I/O blocking while waiting for response/requests from the server.
That being said, I see two possible solutions (only using C# constructs and no specific third party framework) in the library to allow the client to receive requests from the server :
Either offer an event in the library such as
public EventHandler<ReceivedCmdEventArgs> event ReceivedCmd;
that the client would subscribe to, in order to get notidied of requests incoming from the server.
Of course for this mechanism I will have to make an async loop in the client library to receive requests from the server and raise the event on Cmd reception.
Or the other solution would be to make such a method in the client library
public async Task<Cmd> GetNextCmdAsync()
that the client code would call in an async loop to receive the cmds.
Are these solutions kind of the same ? Is it better to fully use async/await constrcuts of C#5 and not rely on events anymore ? What are the differences ? Any recommendation, remark ?
Thanks !
I think that the event-driven approach is better in your case.
In fact, you're talking about an observable/observer pattern. An unknown number of listeners/observers are waiting to do something if some command is received.
Async/await pattern wouldn't work as well as event-driven approach, because it'd be something like I expect one result in opposite to I'll do what you want whenever you report me that you received a command.
Conceptually talking, I prefer the event-driven approach because it fits better with the goal of your architecture.
Async/await pattern in C# 5 isn't designed for your case, but it's for when some code executes an async task and next code lines should be executed after the task has received a result.
Task represents a single asynchronous action, such as receiving a single command. As such, it is not directly suitable for streams of events.
The ultimate library for streams of events is Reactive Extensions (Rx), but it unfortunately has a rather steep learning curve.
A newer option is the lesser-known TPL Dataflow, which allows building up async-friendly dataflow meshes. In fact, I'm writing an async-friendly TCP/IP socket wrapper, and I'm exposing ISourceBlock<ArraySegment<byte>> as the reading stream. The end-user can then either receive from that block directly (ReceiveAsync), or they can just "link" it into a dataflow of their own (e.g., that can do message framing, parsing, and even handling).
Dataflow is slightly less efficient than Rx, but I think the lower learning curve is worth it.
I would not recommend a bare event - you either end up with a free-threaded event (think about how you would handle socket closure - could an event happen after disposal?) or the Event-based Asynchronous Pattern (which has its own similar problems syncing to the provided SynchronizationContext). Both Rx and Dataflow provide better solutions for synchronization and disposal/unsubscription.
Since you are making a library, events seem better suited.
Events allow you to build the library without enforcing that a call back must be specified.
Consumers of your library decide what they are interested in and listen to those events.
Async tasks on the other hand are meant where you know that there will be delays ( IO, Network, etc.) Async tasks allow you to free resources while these delays take place, thus resulting in better utilization of resources.
Async tasks are not a replacement for events that you raise.
I'm in need of some advice in proper coding:
I'm working on a program where multiple serial connections are used. Each communication line has a controller working as an abstraction layer. Between the controller and the serial port, a protocol is inserted to wrap the data in packages, ready for transfer. The protocol takes care of failed deliveries, resending etc.
To ensure that the GUI won't hang, the each connection line (protocol and serial port) is created on a separate thread. The controller is handled by the main thread, since it has controls in the GUI.
Currently, when I create the threads, I have chosen to create a message loop on them (Application.Run()), so instead polling buffers and yielding if no work, i simply invoke the thread (BeginInvoke) and uses the message loop as a buffer. This currently works nicely, and no serious problems so far.
My question is now: Is this "good coding", or should i use a while loop on the tread and be polling buffers instead?, or some third thing?
I would like to show code, but so far it is several thousand lines of code, so please be specific if you need to see any part of the code. :)
Thank you.
Using message loops in each thread is perfectly fine; Windows is optimized for this scenario. You are right to avoid polling, but you may want to look into other event-based designs that are more efficient still, for example preparing a package for transfer and calling SetEvent to notify a thread it's ready, or semaphore and thread-safe queue as Martin James suggests.
I'm not 100% sure what you are doing here but, with a bit of 'filling in' it doesn't sound bad:)
When your app is idle, (no comms), is CPU use 0%?
Is your app free of sleep(0)/sleep(1), or similar, polling loops?
Does it operate with a reasonably low latency?
If the answers are three 'YES', you should be fine :)
There are a few, (very few!), cases where polling for results etc. is a good idea, (eg. when the frequency of events in the threads is so high that signaling every progress event to the GUI would overwhelm it), but mostly, it's just poor design.
I will be using MSMQ in C# to read messages; and I am putting this in Window Service so on OnStart I will start reading messages using queue.Receive method which would be blocking/synchronous call. And OnEnd method I want to stop the queue with queue.Close(); queue.Dispose().
Is there any drawback of this approach ?
Thanks
Ocean
This is incorrect approach. OnStart is called once when service starts, you should put initialization logic. For example start thread that will call Receive in a loop.
This is a fairly common pattern, but it has some drawbacks.
First, you should consider using a thread pool (or the .NET parallel libs in 4.0) to process your messages asynchronously. Whether or not your queue reader can be asynchronous depends a lot on your transaction pattern. Will the processing be atomic?
Second, you should also consider using a timer (System.Timers.Timer) which you start in your OnStart and end in your OnEnd, and which reads one or more messages from the queue on each timer event.
Third, you should seriously consider just using the WCF MSMQ binding, which handles a lot of the complexity of this stuff.
See: http://jamescbender.com/bendersblog/archive/2009/04/04/the-one-where-i-talk-about-the-msmq-binding.aspx
Your approach looks fine to me. My only advice is to make sure that every machine on which you intend to deploy the Windows Service is either in the same Domain, or are in Domains with mutual trust and that reside within the same Forest. I had a problem recently with a solution that I inherited that utilised MSMQ, and that worked much the same way as you have proposed above. It was tested as working on a single domain with no performance issues. Unfortunately, the client was in the process of a merger, and when it came time to implement the solution across the wider company it turned out that the solution had to be implemented on machines that existed in different domains in different Forests, in which case MSMQ wont work at all and another approach entirely had to be used.