websocket-sharp/Example1/Notifier.cs

80 lines
1.6 KiB
C#
Raw Normal View History

2014-03-12 19:23:37 +08:00
#if UBUNTU
using Notifications;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
namespace Example1
{
internal class Notifier : IDisposable
{
2014-03-16 03:25:19 +08:00
private volatile bool _enabled;
2014-03-12 19:23:37 +08:00
private Queue<NotificationMessage> _queue;
2014-03-17 03:04:17 +08:00
private object _sync;
2014-03-12 19:23:37 +08:00
private ManualResetEvent _waitHandle;
public Notifier ()
{
_enabled = true;
_queue = new Queue<NotificationMessage> ();
2014-03-17 03:04:17 +08:00
_sync = ((ICollection) _queue).SyncRoot;
2014-03-12 19:23:37 +08:00
_waitHandle = new ManualResetEvent (false);
ThreadPool.QueueUserWorkItem (
state => {
while (_enabled || Count > 0) {
2014-03-17 03:04:17 +08:00
var msg = dequeue ();
if (msg != null) {
2014-03-12 19:23:37 +08:00
#if UBUNTU
var nf = new Notification (msg.Summary, msg.Body, msg.Icon);
nf.AddHint ("append", "allowed");
nf.Show ();
#else
Console.WriteLine (msg);
#endif
}
2014-10-02 15:16:15 +08:00
else {
2014-03-17 03:04:17 +08:00
Thread.Sleep (500);
2014-10-02 15:16:15 +08:00
}
2014-03-12 19:23:37 +08:00
}
_waitHandle.Set ();
});
}
public int Count {
get {
2014-10-02 15:16:15 +08:00
lock (_sync)
2014-03-12 19:23:37 +08:00
return _queue.Count;
}
}
private NotificationMessage dequeue ()
{
2014-10-02 15:16:15 +08:00
lock (_sync)
2015-11-16 13:41:11 +08:00
return _queue.Count > 0 ? _queue.Dequeue () : null;
2014-03-12 19:23:37 +08:00
}
public void Close ()
{
_enabled = false;
_waitHandle.WaitOne ();
_waitHandle.Close ();
}
public void Notify (NotificationMessage message)
{
2014-10-02 15:16:15 +08:00
lock (_sync)
2014-03-16 03:25:19 +08:00
if (_enabled)
_queue.Enqueue (message);
2014-03-12 19:23:37 +08:00
}
void IDisposable.Dispose ()
{
Close ();
}
}
}