My favorites | Sign in
Repository Home Source
Checkout   Browse   Changes   Clones    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Threading.Tasks;

namespace Stateless
{
/// <summary>Executions queued actions in sequence (but still asynchronously).</summary>
public class SequentialActionQueue : INotifyPropertyChanged
{
private static object syncLock = new object();
private Task firingTask = null;
private ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();
private bool isActive = false;

/// <summary></summary>
public SequentialActionQueue()
{
}

/// <summary>Raised when a property such as <see cref="IsActive"/> is changed.</summary>
public event PropertyChangedEventHandler PropertyChanged;

/// <summary>This property is true when the queue is processing a queued task.</summary>
public bool IsActive
{
get { return this.isActive; }
set
{
if (this.isActive != value)
{
this.isActive = value;
this.OnPropertyChanged("IsActive");
}
}
}

/// <summary>Thread-safe method to synchronize the asynchronous execution of the submitted action.</summary>
/// <param name="todo">The action to execute asynchronously.</param>
public void Enqueue(Action todo)
{
queue.Enqueue(todo);

lock (syncLock)
{
if (firingTask == null || firingTask.IsCompleted)
{
firingTask = Task.Factory.StartNew(() =>
{
this.IsActive = true;

Action result;
while (queue.TryDequeue(out result))
{
result();
}

this.IsActive = false;
});
}
}
}

private void OnPropertyChanged(string propName)
{
var e = this.PropertyChanged;
if (e != null)
{
e(this, new PropertyChangedEventArgs(propName));
}
}
}

}

Change log

4ccd79648b15 by Joel Martinez <joelmartinez> on Jul 15, 2011   Diff
Moved SequentialActionQueue into its own
file.
It is now part of the Stateless library
Go to: 
Project members, sign in to write a code review

Older revisions

All revisions of this file

File info

Size: 2342 bytes, 74 lines
Powered by Google Project Hosting