I'm new to the world of Reactive Extensions and I'm still trying to learn.
I'm developing an app with a datagrid that displays certain running Windows processes and their memory usage. The memory usage of each process should be updated frequently i.e. every 200ms.
Requirements
When checkbox is checked
the datagrid should be filled with processes and the memory usage is updated be using a timer with an interval of 200 ms.
monitor (all should be done on a background thread)
-- if a process has exited, it should be removed from the source.
-- if a process starts, it should be added to the source
-- a file for changes
When checkbox is unchecked
all the monitor activity should be stopped
the datagrid is cleared
Any help would be greatly appreciated!
Notes:
In the past I tried several approaches like using a ObservableConcurrentDictionary as a resource and a timer for periodically updating the resource, but I ran into troubles (concurrency, locking, etc), so I would like to have a solution based on Rx/ReactiveUI
Do to technical limitation I can use only .NET Framework 4.0, Reactive-core.Net40
Update
ViewModel
private ReactiveList<IProcessModel> _processes = new ReactiveList<IProcessModel>() { ChangeTrackingEnabled = true };
public ReactiveList<IProcessModel> Processes { get { return _processes; } }
public MainViewModel(IMonitorService monitorService)
{
this.WhenAnyValue(vm => vm.ShowProcessesIsChecked).Subscribe((b) => DoShowProcesses(b));
}
private void DoShowProcesses(bool checkboxChecked)
{
IDisposable timer;
Processes.Clear();
if (checkboxChecked)
{
//checkbox checked
lock (Processes)
Processes.AddRange(_monitorService.GetProcesses());
timer = Observable.Timer(TimeSpan.FromMilliseconds(200.0))
.Select(x =>
{
lock (Processes)
{
foreach (var process in Processes) //throws the 'Collection was modified; enumeration operation may not execute.'
process.UpdateMemory();
return Processes.Where(p => p.ProcessObject.HasExited).ToList();
}
}).
ObserveOnDispatcher()
.Subscribe(processesExited =>
{
if (processesExited.Count() > 0)
{
lock (Processes)
Processes.RemoveAll(processesExited); //remove all processes that have exited
}
});
}
else
{
if (timer != null)
timer.Dispose();
}
}
I started a new thread
Original
ViewModel
public class MainViewModel : ReactiveObject
{
public ReactiveList<IProcessModel> Processes { get; private set; }
IMonitorService _monitorService;
public MainViewModel(IMonitorService monitorService)
{
_monitorService = monitorService;
Processes = new ReactiveList<IProcessModel>() { ChangeTrackingEnabled = true };
this.WhenAnyValue(vm => vm.ShowProcessesIsChecked)
.Where(value => value == true) //checkbox checked
.ObserveOn(Scheduler.Default) //raise notifications on thread-pool thread to keep UI responsive
.Select((isChecked) =>
{
return monitorService.GetProcesses();
})
.ObserveOn(SynchronizationContext.Current)
.Subscribe(processes => {
Processes.AddRange(processes); }
);
//start the MonitorService with MonitorService.Start(Processes)
//start a timer with an interval of 200ms --> at interval
//- do UpdateMemory() foreach IProcessModel in Processes
//- if ProcessObject.HasExited --> remove it from the collection source
;
this.WhenAnyValue(vm => vm.ShowProcessesIsChecked)
.Where(value => value == false) //checkbox unchecked
.Subscribe((isChecked) =>
{
monitorService.Stop(); //this stops monitoring for starting processes and clears the Processes
});
}
private bool _showProcessesIsChecked;
public bool ShowProcessesIsChecked
{
get { return _showProcessesIsChecked; }
set { this.RaiseAndSetIfChanged(ref _showProcessesIsChecked, value); }
}
}
Model
public class ProcessModel : ProcessModelBase, IProcessModel
{
public ProcessModel(Process process)
{
ProcessObject = process;
}
public void UpdateMemory()
{
try
{
if (!ProcessObject.HasExited)
{
long mem = ProcessObject.PagedMemorySize64;
ProcessObject.Refresh();
if (mem != ProcessObject.PagedMemorySize64)
OnPropertyChanged(nameof(ProcessObject));
}
}
catch (Exception)
{
//log it
}
}
}
Service
public class MonitorService : IMonitorService
{
ManagementEventWatcher managementEventWatcher;
ReactiveList<IProcessModel> _processes;
public List<IProcessModel> GetProcesses()
{
List<IProcessModel> processes = new List<IProcessModel>();
foreach (var process in Process.GetProcesses().Where(p => p.ProcessName.Contains("chrome")))
processes.Add(new ProcessModel(process));
return processes;
}
/// <summary>
/// Starts the manager. Monitor a starting process and changes in log file
/// </summary>
/// <param name="processes"></param>
public void Start(ReactiveList<IProcessModel> processes)
{
_processes = processes;
var qStart = "SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName like 'chrome'";
managementEventWatcher = new ManagementEventWatcher(new WqlEventQuery(qStart));
managementEventWatcher.EventArrived += new EventArrivedEventHandler(OnProcessStarted);
try
{
managementEventWatcher.Start();
}
catch (Exception)
{
//log it
}
Task.Factory.StartNew(() => MonitorLogFile());
}
public void Stop()
{
if (managementEventWatcher != null)
managementEventWatcher.Stop();
if (_processes != null)
_processes.Clear();
}
private void MonitorLogFile()
{
//this code monitors a log file for changes. It is possible that the IsChecked property of a ProcessModel object is set in the Processes collection
}
private void OnProcessStarted(object sender, EventArrivedEventArgs e)
{
try
{
Process process = Process.GetProcessById(Convert.ToInt32(e.NewEvent.Properties["ProcessID"].Value));
_processes.Add(new ProcessModel(process));
}
catch (ArgumentException)
{
//log it
}
catch (InvalidOperationException)
{
//log it
}
}
}
XAML
<CheckBox Content='Show Processes' IsChecked='{Binding ShowProcessesIsChecked}' />
<DataGrid ItemsSource="{Binding Processes}">
<DataGrid.Resources>
<DataGridTemplateColumn Header='Process'
x:Key='dgProcessName'
IsReadOnly='True'
x:Shared='False'>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation='Horizontal' VerticalAlignment='Center'>
<CheckBox IsChecked='{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}' HorizontalAlignment='Stretch' VerticalAlignment='Stretch'> </CheckBox>
<TextBlock Text='{Binding ProcessObject.ProcessName}' />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="PID"
Binding="{Binding ProcessObject.Id}"
IsReadOnly='True'
x:Key='dgPID'
x:Shared='False' />
<DataGridTextColumn Header="Commit Size"
Binding='{Binding ProcessObject.PagedMemorySize64}'
IsReadOnly='True'
x:Key='dgCommitSize'
x:Shared='False' />
</DataGrid.Resources>
</DataGrid>
You basically want to use this kind of pattern:
IObservable<bool> checkBoxChecked = /* your checkbox observable here */
IObservable<long> timer = Observable.Interval(TimeSpan.FromMilliseconds(200.0));
IObservable<long> query =
checkBoxChecked
.Select(x => x ? timer : Observable.Never<long>().StartWith(-1L))
.Switch();
IDisposable subscription =
query
.Subscribe(n =>
{
if (n == -1L)
{
// Clear UI
}
else
{
// Update UI
}
});
This switches between running and not running based on the value of the checkbox.
You need to make sure that you are observing on the UI thread, but other than some minor tweaking then this should work fine.
I wanted to practice my Rx skills anyways, so I went ahead and created a WPF project and gave it a shot. I got it working so I'll share how I went about it.
Remove the process list from MonitorService. This will help isolate the source of list modifications, making our debugging life easier. It also narrows MonitorService's responsibilities down to providing the initial list and emitting changes.
We're already "being reactive" so we may as well turn the EventArrived event into an observable, too, using FromEventPattern. Then we can transform those fired events into ProcessModels and push them out to the subscriber(s).
I moved the ManagementEventWatcher creation to the constructor, so we don't have to recreate it every time the checkbox is checked. Now the Start/Stop methods are now simply wrappers for the _managementEventWatcher versions.
.
public class MonitorService
{
ManagementEventWatcher _managementEventWatcher;
public IObservable<ProcessModel> NewProcessObservable { get; }
public MonitorService()
{
var qStart = "SELECT * FROM Win32_ProcessStartTrace where ProcessName='chrome.exe'";
_managementEventWatcher = new ManagementEventWatcher(new WqlEventQuery(qStart));
var eventArrivedObservable = Observable.FromEventPattern<EventArrivedEventHandler, EventArrivedEventArgs>(
x => _managementEventWatcher.EventArrived += x,
x => _managementEventWatcher.EventArrived -= x);
NewProcessObservable = eventArrivedObservable
.Select(x => GetProcessModel(x.EventArgs))
.Where(x => x != null);
}
public List<ProcessModel> GetProcesses()
{
List<ProcessModel> processes = new List<ProcessModel>();
foreach(var process in Process.GetProcesses().Where(p => p.ProcessName.Contains("chrome")))
processes.Add(new ProcessModel(process));
return processes;
}
public void Start()
{
try
{
_managementEventWatcher.Start();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Stop()
{
if(_managementEventWatcher != null)
_managementEventWatcher.Stop();
}
private ProcessModel GetProcessModel(EventArrivedEventArgs e)
{
ProcessModel model = null;
try
{
Process process = Process.GetProcessById(Convert.ToInt32(e.NewEvent.Properties["ProcessID"].Value));
model = new ProcessModel(process);
}
catch(ArgumentException)
{
//log it
}
catch(InvalidOperationException)
{
//log it
}
return model;
}
}
MainViewModel
To avoid errors such as 'Collection was modified; enumeration operation may not execute' a simple solution is to iterate backward using a for loop.
Immediately preceding each subscribe call, use .ObserveOnDispatcher() so the onNext calls will execute on the UI thread. The cool part is that the only place we're modifying the list, now, is inside subscribe. So, we don't have to use locks and all that.
I divided the logic into 3 different subscriptions: Start/stop the monitoring, Update the memory usage and remove processes that have exited (used #Enigmativity's suggested pattern), and add newly started processes to our reactive list. Hopefully, this makes it easy to follow the logic.
.
public class MainViewModel : ReactiveObject
{
public ReactiveList<ProcessModel> Processes { get; private set; }
MonitorService _monitorService;
public MainViewModel(MonitorService monitorService)
{
_monitorService = monitorService;
Processes = new ReactiveList<ProcessModel>() { ChangeTrackingEnabled = true };
RxApp.SupportsRangeNotifications = false;
IObservable<bool> checkboxObservable = this.WhenAnyValue(vm => vm.ShowProcessesIsChecked);
IObservable<long> intervalObservable = Observable.Interval(TimeSpan.FromMilliseconds(200.0));
// Start/stop the monitoring.
checkboxObservable
// Skip the default unchecked state.
.Skip(1)
.ObserveOnDispatcher()
.Subscribe(
isChecked =>
{
if(isChecked)
{
Processes.AddRange(monitorService.GetProcesses());
monitorService.Start();
}
else
{
Processes.Clear();
monitorService.Stop();
}
});
// Update the memory usage and remove processes that have exited.
checkboxObservable
.Select(isChecked => isChecked ? intervalObservable : Observable.Never<long>())
// Switch disposes of the previous internal observable
// (either intervalObservable or Never) and "switches" to the new one.
.Switch()
.ObserveOnDispatcher()
.Subscribe(
_ =>
{
// Loop backwards in a normal for-loop to avoid the modification errors.
for(int i = Processes.Count - 1; i >= 0; --i)
{
if(Processes[i].ProcessObject.HasExited)
{
Processes.RemoveAt(i);
}
else
{
Processes[i].UpdateMemory();
}
}
});
// Add newly started processes to our reactive list.
monitorService.NewProcessObservable
.Where(_ => ShowProcessesIsChecked)
.ObserveOnDispatcher()
.Subscribe(process => Processes.Add(process));
}
private bool _showProcessesIsChecked;
public bool ShowProcessesIsChecked
{
get { return _showProcessesIsChecked; }
set { this.RaiseAndSetIfChanged(ref _showProcessesIsChecked, value); }
}
}
More info
If this is the only page/window in you application, then this is enough. If not, you have a little more work to do, to avoid memory leaks. In the latter case, I recommend Google searching "ReactiveUI WhenActivated" (and maybe even throw wpf in there). You'll find lots of examples that you can use and learn from.
I'm writting a control software / HMI using this ua-client for WPF, with Kepwere as OPC Server.
Today I was doing some connection tests, disconnecting the ethernet cable of my PLC and change some monitored item value in the software. Obviously this change wont take effect because the connection state, but, after reconnect why don't refresh the PLC tag with the value that I previously set?
Or this is the expected behavior and I need to make some internal storage variable to replicate this?
Kepserver have a System.NoError Tag that indicate if there is an error on the PLC, so I know when the PLC is offline. But I'm trying to resend the latest change while was offline whe it reconnect.
I overwrote the SetProperty method:
protected override bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if(ServerState != CommunicationState.Opened || (!System_NoError && "System_NoError" != propertyName))
{
m_eventsPending.Add(new WriteEvent
{
PropertyName = propertyName,
PropertyValue = value
});
return false;
}
return base.SetProperty(ref storage, value, propertyName);
}
And then listen to the server state change event with this:
public void OnStateChangeEvent(CommunicationState state)
{
ServerState = state;
}
On every change on System_NoError I do:
private void OnError()
{
if(System_NoError)
{
while(m_eventsPending.Count > 0)
{
WriteEvent e = m_eventsPending.ElementAt(0);
bool storage = !(bool)e.PropertyValue;
var p = this.GetType().GetProperty(e.PropertyName);
p.SetValue(this, storage);
p.SetValue(this, e.PropertyValue);
m_eventsPending.RemoveAt(0);
}
}
}
I do some initialization and keep it on the m_eventsPending list, and start sending when connection is complete (Opened), but nothing happend on the PLC side. What could be wrong?
P.S: Any other interaction with the software make the correct change on the PLC, acording to my code (buttons, slider, etc)
Best Regards
Jose Truyol
Consider writing the tag directly in the property setter. This example tries writing the Green light, retrying every 5 seconds until successful.
public class TrafficLightViewModel : ViewModelBase
{
private bool green;
private bool red;
private bool yellow;
private CancellationTokenSource greenCts;
private CancellationTokenSource redCts;
private CancellationTokenSource yellowCts;
private UaTcpSessionClient session;
public TrafficLightViewModel(UaTcpSessionClient session)
{
this.session = session;
}
public bool Green
{
get { return this.green; }
set
{
this.green = value;
this.greenCts?.Cancel();
this.greenCts = new CancellationTokenSource();
var request = new WriteRequest
{
NodesToWrite = new[]
{
new WriteValue
{
NodeId = NodeId.Parse("ns=2;s=GreenLight"),
AttributeId = AttributeIds.Value,
Value = new DataValue(value)
}
}
};
this.WriteOutputAsync(request, this.greenCts.Token);
}
}
// add yellow and red
private async void WriteOutputAsync(WriteRequest request, CancellationToken token)
{
try
{
while (!await this.TryWriteAsync(request))
{
await Task.Delay(5000, token);
}
}
catch (TaskCanceledException)
{
Debug.WriteLine($"Canceled writing output : {request.NodesToWrite[0].NodeId}");
}
}
private async Task<bool> TryWriteAsync(WriteRequest request)
{
try
{
var response = await this.session.WriteAsync(request);
for (int i = 0; i < response.Results.Length; i++)
{
if (StatusCode.IsBad(response.Results[i]))
{
Debug.WriteLine($"Error writing output '{request.NodesToWrite[i].NodeId}' {request.NodesToWrite[i].Value.GetValue()}: {StatusCodes.GetDefaultMessage(response.Results[i])}");
return false;
}
}
return true;
}
catch (Exception ex)
{
Debug.WriteLine($"Error writing outputs : {ex.Message}");
return false;
}
}
}
Hope this helps.
Andrew
I'm listening to a hardware event message, but I need to debounce it to avoid too many queries.
This is an hardware event that sends the machine status and I have to store it in a database for statistical purposes, and it sometimes happens that its status changes very often (flickering?). In this case I would like to store only a "stable" status and I want to implement it by simply waiting for 1-2s before storing the status to the database.
This is my code:
private MachineClass connect()
{
try
{
MachineClass rpc = new MachineClass();
rpc.RxVARxH += eventRxVARxH;
return rpc;
}
catch (Exception e1)
{
log.Error(e1.Message);
return null;
}
}
private void eventRxVARxH(MachineClass Machine)
{
log.Debug("Event fired");
}
I call this behaviour "debounce": wait a few times to really do its job: if the same event is fired again during the debounce time, I have to dismiss the first request and start to wait the debounce time to complete the second event.
What is the best choice to manage it? Simply a one-shot timer?
To explain the "debounce" function please see this javascript implementation for key events:
http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/
I've used this to debounce events with some success:
public static Action<T> Debounce<T>(this Action<T> func, int milliseconds = 300)
{
var last = 0;
return arg =>
{
var current = Interlocked.Increment(ref last);
Task.Delay(milliseconds).ContinueWith(task =>
{
if (current == last) func(arg);
task.Dispose();
});
};
}
Usage
Action<int> a = (arg) =>
{
// This was successfully debounced...
Console.WriteLine(arg);
};
var debouncedWrapper = a.Debounce<int>();
while (true)
{
var rndVal = rnd.Next(400);
Thread.Sleep(rndVal);
debouncedWrapper(rndVal);
}
It may not be a robust as what's in RX but it's easy to understand and use.
Followup 2020-02-03
Revised #collie's solution using cancellation tokens as follows
public static Action<T> Debounce<T>(this Action<T> func, int milliseconds = 300)
{
CancellationTokenSource? cancelTokenSource = null;
return arg =>
{
cancelTokenSource?.Cancel();
cancelTokenSource = new CancellationTokenSource();
Task.Delay(milliseconds, cancelTokenSource.Token)
.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
{
func(arg);
}
}, TaskScheduler.Default);
};
}
Notes:
Calling Cancel is enough to dispose of the CTS
A successfully completed CTS is not canceled/disposed until the next call
As noted by #collie, tasks get disposed so no need to call Dispose on the task
I've not worked with cancellation tokens before and may not be using them correctly.
This isn't a trivial request to code from scratch as there are several nuances. A similar scenario is monitoring a FileSystemWatcher and waiting for things to quiet down after a big copy, before you try to open the modified files.
Reactive Extensions in .NET 4.5 were created to handle exactly these scenarios. You can use them easily to provide such functionality with methods like Throttle, Buffer, Window or Sample. You post the events to a Subject, apply one of the windowing functions to it, for example to get a notification only if there was no activity for X seconds or Y events, then subscribe to the notification.
Subject<MyEventData> _mySubject=new Subject<MyEventData>();
....
var eventSequenc=mySubject.Throttle(TimeSpan.FromSeconds(1))
.Subscribe(events=>MySubscriptionMethod(events));
Throttle returns the last event in a sliding window, only if there were no other events in the window. Any event resets the window.
You can find a very good overview of the time-shifted functions here
When your code receives the event, you only need to post it to the Subject with OnNext:
_mySubject.OnNext(MyEventData);
If your hardware event surfaces as a typical .NET Event, you can bypass the Subject and manual posting with Observable.FromEventPattern, as shown here:
var mySequence = Observable.FromEventPattern<MyEventData>(
h => _myDevice.MyEvent += h,
h => _myDevice.MyEvent -= h);
_mySequence.Throttle(TimeSpan.FromSeconds(1))
.Subscribe(events=>MySubscriptionMethod(events));
You can also create observables from Tasks, combine event sequences with LINQ operators to request eg: pairs of different hardware events with Zip, use another event source to bound Throttle/Buffer etc, add delays and a lot more.
Reactive Extensions is available as a NuGet package, so it's very easy to add them to your project.
Stephen Cleary's book "Concurrency in C# Cookbook" is a very good resource on Reactive Extensions among other things, and explains how you can use it and how it fits with the rest of the concurrent APIs in .NET like Tasks, Events etc.
Introduction to Rx is an excellent series of articles (that's where I copied the samples from), with several examples.
UPDATE
Using your specific example, you could do something like:
IObservable<MachineClass> _myObservable;
private MachineClass connect()
{
MachineClass rpc = new MachineClass();
_myObservable=Observable
.FromEventPattern<MachineClass>(
h=> rpc.RxVARxH += h,
h=> rpc.RxVARxH -= h)
.Throttle(TimeSpan.FromSeconds(1));
_myObservable.Subscribe(machine=>eventRxVARxH(machine));
return rpc;
}
This can be improved vastly of course - both the observable and the subscription need to be disposed at some point. This code assumes that you only control a single device. If you have many devices, you could create the observable inside the class so that each MachineClass exposes and disposes its own observable.
Recently I was doing some maintenance on an application that was targeting an older version of the .NET framework (v3.5).
I couldn't use Reactive Extensions nor Task Parallel Library, but I needed a nice, clean, consistent way of debouncing events. Here's what I came up with:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace MyApplication
{
public class Debouncer : IDisposable
{
readonly TimeSpan _ts;
readonly Action _action;
readonly HashSet<ManualResetEvent> _resets = new HashSet<ManualResetEvent>();
readonly object _mutex = new object();
public Debouncer(TimeSpan timespan, Action action)
{
_ts = timespan;
_action = action;
}
public void Invoke()
{
var thisReset = new ManualResetEvent(false);
lock (_mutex)
{
while (_resets.Count > 0)
{
var otherReset = _resets.First();
_resets.Remove(otherReset);
otherReset.Set();
}
_resets.Add(thisReset);
}
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
if (!thisReset.WaitOne(_ts))
{
_action();
}
}
finally
{
lock (_mutex)
{
using (thisReset)
_resets.Remove(thisReset);
}
}
});
}
public void Dispose()
{
lock (_mutex)
{
while (_resets.Count > 0)
{
var reset = _resets.First();
_resets.Remove(reset);
reset.Set();
}
}
}
}
}
Here's an example of using it in a windows form that has a search text box:
public partial class Example : Form
{
private readonly Debouncer _searchDebouncer;
public Example()
{
InitializeComponent();
_searchDebouncer = new Debouncer(TimeSpan.FromSeconds(.75), Search);
txtSearchText.TextChanged += txtSearchText_TextChanged;
}
private void txtSearchText_TextChanged(object sender, EventArgs e)
{
_searchDebouncer.Invoke();
}
private void Search()
{
if (InvokeRequired)
{
Invoke((Action)Search);
return;
}
if (!string.IsNullOrEmpty(txtSearchText.Text))
{
// Search here
}
}
}
I ran into issues with this. I tried each of the answers here, and since I'm in a Xamarin universal app, I seem to be missing certain things that are required in each of these answers, and I didn't want to add any more packages or libraries. My solution works exactly how I'd expect it to, and I haven't run into any issues with it. Hope it helps somebody.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace OrderScanner.Models
{
class Debouncer
{
private List<CancellationTokenSource> StepperCancelTokens = new List<CancellationTokenSource>();
private int MillisecondsToWait;
private readonly object _lockThis = new object(); // Use a locking object to prevent the debouncer to trigger again while the func is still running
public Debouncer(int millisecondsToWait = 300)
{
this.MillisecondsToWait = millisecondsToWait;
}
public void Debouce(Action func)
{
CancelAllStepperTokens(); // Cancel all api requests;
var newTokenSrc = new CancellationTokenSource();
lock (_lockThis)
{
StepperCancelTokens.Add(newTokenSrc);
}
Task.Delay(MillisecondsToWait, newTokenSrc.Token).ContinueWith(task => // Create new request
{
if (!newTokenSrc.IsCancellationRequested) // if it hasn't been cancelled
{
CancelAllStepperTokens(); // Cancel any that remain (there shouldn't be any)
StepperCancelTokens = new List<CancellationTokenSource>(); // set to new list
lock (_lockThis)
{
func(); // run
}
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
private void CancelAllStepperTokens()
{
foreach (var token in StepperCancelTokens)
{
if (!token.IsCancellationRequested)
{
token.Cancel();
}
}
}
}
}
It's called like so...
private Debouncer StepperDeboucer = new Debouncer(1000); // one second
StepperDeboucer.Debouce(() => { WhateverMethod(args) });
I wouldn't recommend this for anything where the machine could be sending in hundreds of requests a second, but for user input, it works excellently. I'm using it on a stepper in an android/IOS app that calls to an api on step.
RX is probably the easiest choice, especially if you're already using it in your application. But if not, adding it might be a bit of overkill.
For UI based applications (like WPF) I use the following class that use DispatcherTimer:
public class DebounceDispatcher
{
private DispatcherTimer timer;
private DateTime timerStarted { get; set; } = DateTime.UtcNow.AddYears(-1);
public void Debounce(int interval, Action<object> action,
object param = null,
DispatcherPriority priority = DispatcherPriority.ApplicationIdle,
Dispatcher disp = null)
{
// kill pending timer and pending ticks
timer?.Stop();
timer = null;
if (disp == null)
disp = Dispatcher.CurrentDispatcher;
// timer is recreated for each event and effectively
// resets the timeout. Action only fires after timeout has fully
// elapsed without other events firing in between
timer = new DispatcherTimer(TimeSpan.FromMilliseconds(interval), priority, (s, e) =>
{
if (timer == null)
return;
timer?.Stop();
timer = null;
action.Invoke(param);
}, disp);
timer.Start();
}
}
To use it:
private DebounceDispatcher debounceTimer = new DebounceDispatcher();
private void TextSearchText_KeyUp(object sender, KeyEventArgs e)
{
debounceTimer.Debounce(500, parm =>
{
Model.AppModel.Window.ShowStatus("Searching topics...");
Model.TopicsFilter = TextSearchText.Text;
Model.AppModel.Window.ShowStatus();
});
}
Key events are now only processed after keyboard is idle for 200ms - any previous pending events are discarded.
There's also a Throttle method which always fires events after a given interval:
public void Throttle(int interval, Action<object> action,
object param = null,
DispatcherPriority priority = DispatcherPriority.ApplicationIdle,
Dispatcher disp = null)
{
// kill pending timer and pending ticks
timer?.Stop();
timer = null;
if (disp == null)
disp = Dispatcher.CurrentDispatcher;
var curTime = DateTime.UtcNow;
// if timeout is not up yet - adjust timeout to fire
// with potentially new Action parameters
if (curTime.Subtract(timerStarted).TotalMilliseconds < interval)
interval = (int) curTime.Subtract(timerStarted).TotalMilliseconds;
timer = new DispatcherTimer(TimeSpan.FromMilliseconds(interval), priority, (s, e) =>
{
if (timer == null)
return;
timer?.Stop();
timer = null;
action.Invoke(param);
}, disp);
timer.Start();
timerStarted = curTime;
}
Panagiotis's answer is certainly correct, however I wanted to give a simpler example, as it took me a while to sort through how to get it working. My scenario is that a user types in a search box, and as the user types we want to make api calls to return search suggestions, so we want to debounce the api calls so they don't make one every time they type a character.
I'm using Xamarin.Android, however this should apply to any C# scenario...
private Subject<string> typingSubject = new Subject<string> ();
private IDisposable typingEventSequence;
private void Init () {
var searchText = layoutView.FindViewById<EditText> (Resource.Id.search_text);
searchText.TextChanged += SearchTextChanged;
typingEventSequence = typingSubject.Throttle (TimeSpan.FromSeconds (1))
.Subscribe (query => suggestionsAdapter.Get (query));
}
private void SearchTextChanged (object sender, TextChangedEventArgs e) {
var searchText = layoutView.FindViewById<EditText> (Resource.Id.search_text);
typingSubject.OnNext (searchText.Text.Trim ());
}
public override void OnDestroy () {
if (typingEventSequence != null)
typingEventSequence.Dispose ();
base.OnDestroy ();
}
When you first initialize the screen / class, you create your event to listen to the user typing (SearchTextChanged), and then also set up a throttling subscription, which is tied to the "typingSubject".
Next, in your SearchTextChanged event, you can call typingSubject.OnNext and pass in the search box's text. After the debounce period (1 second), it will call the subscribed event (suggestionsAdapter.Get in our case.)
Lastly, when the screen is closed, make sure to dispose of the subscription!
This little gem is inspired by Mike Wards diabolically ingenious extension attempt. However, this one cleans up after itself quite nicely.
public static Action Debounce(this Action action, int milliseconds = 300)
{
CancellationTokenSource lastCToken = null;
return () =>
{
//Cancel/dispose previous
lastCToken?.Cancel();
try {
lastCToken?.Dispose();
} catch {}
var tokenSrc = lastCToken = new CancellationTokenSource();
Task.Delay(milliseconds).ContinueWith(task => { action(); }, tokenSrc.Token);
};
}
Note: there's no need to dispose of the task in this case. See here for the evidence.
Usage
Action DebounceToConsole;
int count = 0;
void Main()
{
//Assign
DebounceToConsole = ((Action)ToConsole).Debounce(50);
var random = new Random();
for (int i = 0; i < 50; i++)
{
DebounceToConsole();
Thread.Sleep(random.Next(100));
}
}
public void ToConsole()
{
Console.WriteLine($"I ran for the {++count} time.");
}
I needed something like this but in a web-application, so I can't store the Action in a variable, it will be lost between http requests.
Based on other answers and #Collie idea I created a class that looks at a unique string key for throttling.
public static class Debouncer
{
static ConcurrentDictionary<string, CancellationTokenSource> _tokens = new ConcurrentDictionary<string, CancellationTokenSource>();
public static void Debounce(string uniqueKey, Action action, int seconds)
{
var token = _tokens.AddOrUpdate(uniqueKey,
(key) => //key not found - create new
{
return new CancellationTokenSource();
},
(key, existingToken) => //key found - cancel task and recreate
{
existingToken.Cancel(); //cancel previous
return new CancellationTokenSource();
}
);
Task.Delay(seconds * 1000, token.Token).ContinueWith(task =>
{
if (!task.IsCanceled)
{
action();
_tokens.TryRemove(uniqueKey, out _);
}
}, token.Token);
}
}
Usage:
//throttle for 5 secs if it's already been called with this KEY
Debouncer.Debounce("Some-Unique-ID", () => SendEmails(), 5);
As a side bonus, because it's based on a string key, you can use inline lambda's
Debouncer.Debounce("Some-Unique-ID", () =>
{
//do some work here
}, 5);
Created this class for solving it also for awaitable calls:
public class Debouncer
{
private CancellationTokenSource _cancelTokenSource = null;
public async Task Debounce(Func<Task> method, int milliseconds = 300)
{
_cancelTokenSource?.Cancel();
_cancelTokenSource?.Dispose();
_cancelTokenSource = new CancellationTokenSource();
await Task.Delay(milliseconds, _cancelTokenSource.Token);
await method();
}
}
Sample of use:
private Debouncer _debouncer = new Debouncer();
....
await _debouncer.Debounce(YourAwaitableMethod);
This is inspired by Nieminen's Task.Delay-based Debouncer class. Simplified, some minor corrections, and should clean up after itself better.
class Debouncer: IDisposable
{
private CancellationTokenSource lastCToken;
private int milliseconds;
public Debouncer(int milliseconds = 300)
{
this.milliseconds = milliseconds;
}
public void Debounce(Action action)
{
Cancel(lastCToken);
var tokenSrc = lastCToken = new CancellationTokenSource();
Task.Delay(milliseconds).ContinueWith(task =>
{
action();
},
tokenSrc.Token
);
}
public void Cancel(CancellationTokenSource source)
{
if (source != null)
{
source.Cancel();
source.Dispose();
}
}
public void Dispose()
{
Cancel(lastCToken);
}
~Debouncer()
{
Dispose();
}
}
Usage
private Debouncer debouncer = new Debouncer(500); //1/2 a second
...
debouncer.Debounce(SomeAction);
I needed a Debounce method for Blazor and kept coming back to this page so I wanted to share my solution in case it helps others.
public class DebounceHelper
{
private CancellationTokenSource debounceToken = null;
public async Task DebounceAsync(Func<CancellationToken, Task> func, int milliseconds = 1000)
{
try
{
// Cancel previous task
if (debounceToken != null) { debounceToken.Cancel(); }
// Assign new token
debounceToken = new CancellationTokenSource();
// Debounce delay
await Task.Delay(milliseconds, debounceToken.Token);
// Throw if canceled
debounceToken.Token.ThrowIfCancellationRequested();
// Run function
await func(debounceToken.Token);
}
catch (TaskCanceledException) { }
}
}
Example call on a search function
<input type="text" #oninput=#(async (eventArgs) => await OnSearchInput(eventArgs)) />
#code {
private readonly DebounceHelper debouncer = new DebounceHelper();
private async Task OnSearchInput(ChangeEventArgs eventArgs)
{
await debouncer.DebounceAsync(async (cancellationToken) =>
{
// Search Code Here
});
}
}
Simply remember the latest 'hit:
DateTime latestHit = DatetIme.MinValue;
private void eventRxVARxH(MachineClass Machine)
{
log.Debug("Event fired");
if(latestHit - DateTime.Now < TimeSpan.FromXYZ() // too fast
{
// ignore second hit, too fast
return;
}
latestHit = DateTime.Now;
// it was slow enough, do processing
...
}
This will allow a second event if there was enough time after the last event.
Please note: it is not possible (in a simple way) to handle the last event in a series of fast events, because you never know which one is the last...
...unless you are prepared to handle the last event of a burst which is a long time ago. Then you have to remember the last event and log it if the next event is slow enough:
DateTime latestHit = DatetIme.MinValue;
Machine historicEvent;
private void eventRxVARxH(MachineClass Machine)
{
log.Debug("Event fired");
if(latestHit - DateTime.Now < TimeSpan.FromXYZ() // too fast
{
// ignore second hit, too fast
historicEvent = Machine; // or some property
return;
}
latestHit = DateTime.Now;
// it was slow enough, do processing
...
// process historicEvent
...
historicEvent = Machine;
}
I did some more simple solution based on #Mike Ward answer:
public static class CustomTaskExtension
{
#region fields
private static int _last = 0;
#endregion
public static void Debounce(CancellationTokenSource throttleCts, double debounceTimeMs, Action action)
{
var current = Interlocked.Increment(ref _last);
Task.Delay(TimeSpan.FromMilliseconds(debounceTimeMs), throttleCts.Token)
.ContinueWith(task =>
{
if (current == _last) action();
task.Dispose();
});
}
}
Example how to use it:
// security way to cancel the debounce process any time
CancellationTokenSource _throttleCts = new CancellationTokenSource();
public void MethodCalledManyTimes()
{
// will wait 250ms after the last call
CustomTaskExtension.Debounce(_throttleCts, 250, async () =>
{
Console.Write("Execute your code 250ms after the last call.");
});
}
I came up with this in my class definition.
I wanted to run my action immediately if there hasn't been any action for the time period (3 seconds in the example).
If something has happened in the last three seconds, I want to send the last thing that happened within that time.
private Task _debounceTask = Task.CompletedTask;
private volatile Action _debounceAction;
/// <summary>
/// Debounces anything passed through this
/// function to happen at most every three seconds
/// </summary>
/// <param name="act">An action to run</param>
private async void DebounceAction(Action act)
{
_debounceAction = act;
await _debounceTask;
if (_debounceAction == act)
{
_debounceTask = Task.Delay(3000);
act();
}
}
So, if I have subdivide my clock into every quarter of a second
TIME: 1e&a2e&a3e&a4e&a5e&a6e&a7e&a8e&a9e&a0e&a
EVENT: A B C D E F
OBSERVED: A B E F
Note that no attempt is made to cancel the task early, so it's possible for actions to pile up for 3 seconds before eventually being available for garbage collection.
Figured out how to use System.Reactive NuGet package for doing a proper debouncing on a TextBox.
At the class level, we have our field
private IObservable<EventPattern<TextChangedEventArgs>> textChanged;
Then when we want to start listening to the event:
// Debouncing capability
textChanged = Observable.FromEventPattern<TextChangedEventArgs>(txtSearch, "TextChanged");
textChanged.ObserveOnDispatcher().Throttle(TimeSpan.FromSeconds(1)).Subscribe(args => {
Debug.WriteLine("bounce!");
});
Make sure you don't also wire your textbox up to an event handler. The Lambda above is the event handler.
I wrote an async debouncer that doesn't run async-in-sync.
public sealed class Debouncer : IDisposable {
public Debouncer(TimeSpan? delay) => _delay = delay ?? TimeSpan.FromSeconds(2);
private readonly TimeSpan _delay;
private CancellationTokenSource? previousCancellationToken = null;
public async Task Debounce(Action action) {
_ = action ?? throw new ArgumentNullException(nameof(action));
Cancel();
previousCancellationToken = new CancellationTokenSource();
try {
await Task.Delay(_delay, previousCancellationToken.Token);
await Task.Run(action, previousCancellationToken.Token);
}
catch (TaskCanceledException) { } // can swallow exception as nothing more to do if task cancelled
}
public void Cancel() {
if (previousCancellationToken != null) {
previousCancellationToken.Cancel();
previousCancellationToken.Dispose();
}
}
public void Dispose() => Cancel();
}
I use it to debounce changes reported on file changes, see complete example here.
I was inspired by Mike's answer, but needed solution that worked without tasks, which simply swallows subsequent event invocations until debounce time-out runs out. Here's my solution:
public static Action<T> Debounce<T>(this Action<T> action, int milliseconds = 300)
{
DateTime? runningCallTime = null;
var locker = new object();
return arg =>
{
lock (locker)
{
if (!runningCallTime.HasValue ||
runningCallTime.Value.AddMilliseconds(milliseconds) <= DateTime.UtcNow)
{
runningCallTime = DateTime.UtcNow;
action.Invoke(arg);
}
}
};
}
Another implementation
public static class Debounce
{
public static Action Action(Action action, TimeSpan time)
{
var timer = new Timer(_ => action(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
return () => timer.Change(time, Timeout.InfiniteTimeSpan);
}
}
None of the above answers fully worked for me, so I've come up with the following implementation:
public class Debouncer
{
private CancellationTokenSource _cancelTokenSource = null;
public Task Debounce(Func<Task> method, int milliseconds = 250)
{
_cancelTokenSource?.Cancel();
_cancelTokenSource?.Dispose();
_cancelTokenSource = new CancellationTokenSource();
try
{
return Task.Delay(milliseconds, _cancelTokenSource.Token)
.ContinueWith(_ => method(), _cancelTokenSource.Token);
}
catch (TaskCanceledException exception) when (exception.CancellationToken == _cancelTokenSource.Token)
{
}
return Task.CompletedTask;
}
}
Usage:
var debouncer = new Debouncer();
await debouncer.Debounce(async () => await someAction());
I know I'm a couple hundred thousand minutes late to this party but I figured I'd add my 2 cents. I'm surprised no one has suggested this so I'm assuming there's something I don't know that might make it less than ideal so maybe I'll learn something new if this gets shot down.
I often use a solution that uses the System.Threading.Timer's Change() method.
using System.Threading;
Timer delayedActionTimer;
public MyClass()
{
// Setup our timer
delayedActionTimer = new Timer(saveOrWhatever, // The method to call when triggered
null, // State object (Not required)
Timeout.Infinite, // Start disabled
Timeout.Infinite); // Don't repeat the trigger
}
// A change was made that we want to save but not until a
// reasonable amount of time between changes has gone by
// so that we're not saving on every keystroke/trigger event.
public void TextChanged()
{
delayedActionTimer.Change(3000, // Trigger this timers function in 3 seconds,
// overwriting any existing countdown
Timeout.Infinite); // Don't repeat this trigger; Only fire once
}
// Timer requires the method take an Object which we've set to null since we don't
// need it for this example
private void saveOrWhatever(Object obj)
{
/*Do the thing*/
}
Update - solved
The final solution differs a bit from Brandon's suggestion but his answer brought me on the right track.
class State
{
public int Offset { get; set; }
public HashSet<string> UniqueImageUrls = new HashSet<string>();
}
public IObservable<TPicture> GetPictures(ref object _state)
{
var localState = (State) _state ?? new State();
_state = localState;
return Observable.Defer(()=>
{
return Observable.Defer(() => Observable.Return(GetPage(localState.Offset)))
.SubscribeOn(TaskPoolScheduler.Default)
.Do(x=> localState.Offset += 20)
.Repeat()
.TakeWhile(x=> x.Count > 0)
.SelectMany(x=> x)
.Where(x=> !localState.UniqueImageUrls.Contains(x.ImageUrl))
.Do(x=> localState.UniqueImageUrls.Add(x.ImageUrl));
});
}
IList<TPicture> GetPage(int offset)
{
...
return result;
}
Original Question
I'm currently struggling with the following problem. The PictureProvider implementation shown below is working with an offset variable used for paging results of a backend service providing the actual data. What I would like to implement is an elegant solution making the current offset available to the consumer of the observable to allow for resuming the observable sequence at a later time at the correct offset. Resuming is already accounted for by the intialState argument to GetPictures().
Recommendations for improving the code in a more RX like fashion would be welcome as well. I'm actually not so sure if the Task.Run() stuff is appropriate here.
public class PictureProvider :
IPictureProvider<Picture>
{
#region IPictureProvider implementation
public IObservable<Picture> GetPictures(object initialState)
{
return Observable.Create<Picture>((IObserver<Picture> observer) =>
{
var state = new ProducerState(initialState);
ProducePictures(observer, state);
return state;
});
}
#endregion
void ProducePictures(IObserver<Picture> observer, ProducerState state)
{
Task.Run(() =>
{
try
{
while(!state.Terminate.WaitOne(0))
{
var page = GetPage(state.Offset);
if(page.Count == 0)
{
observer.OnCompleted();
break;
}
else
{
foreach(var picture in page)
observer.OnNext(picture);
state.Offset += page.Count;
}
}
}
catch (Exception ex)
{
observer.OnError(ex);
}
state.TerminateAck.Set();
});
}
IList<Picture> GetPage(int offset)
{
var result = new List<Picture>();
... boring web service call here
return result;
}
public class ProducerState :
IDisposable
{
public ProducerState(object initialState)
{
Terminate = new ManualResetEvent(false);
TerminateAck = new ManualResetEvent(false);
if(initialState != null)
Offset = (int) initialState;
}
public ManualResetEvent Terminate { get; private set; }
public ManualResetEvent TerminateAck { get; private set; }
public int Offset { get; set; }
#region IDisposable implementation
public void Dispose()
{
Terminate.Set();
TerminateAck.WaitOne();
Terminate.Dispose();
TerminateAck.Dispose();
}
#endregion
}
}
I suggest refactoring your interface to yield the state as part of the data. Now the client has what they need to resubscribe where they left off.
Also, once you start using Rx, you should find that using synchronization primitives like ManualResetEvent are rarely necessary. If you refactor your code so that retrieving each page is its own Task, then you can eliminate all of that synchronization code.
Also, if you are calling a "boring web service" in GetPage, then just make it async. This gets rid of the need to call Task.Run among other benefits.
Here is a refactored version, using .NET 4.5 async/await syntax. It could also be done without async/await. I also added a GetPageAsync method that uses Observable.Run just in case you really cannot convert your webservice call to be asynchronous
/// <summary>A set of pictures</summary>
public struct PictureSet
{
public int Offset { get; private set; }
public IList<Picture> Pictures { get; private set; }
/// <summary>Clients will use this property if they want to pick up where they left off</summary>
public int NextOffset { get { return Offset + Pictures.Count; } }
public PictureSet(int offset, IList<Picture> pictures)
:this() { Offset = offset; Pictures = pictures; }
}
public class PictureProvider : IPictureProvider<PictureSet>
{
public IObservable<PictureSet> GetPictures(int offset = 0)
{
// use Defer() so we can capture a copy of offset
// for each observer that subscribes (so multiple
// observers do not update each other's offset
return Observable.Defer<PictureSet>(() =>
{
var localOffset = offset;
// Use Defer so we re-execute GetPageAsync()
// each time through the loop.
// Update localOffset after each GetPageAsync()
// completes so that the next call to GetPageAsync()
// uses the next offset
return Observable.Defer(() => GetPageAsync(localOffset))
.Select(pictures =>
{
var s = new PictureSet(localOffset, pictures);
localOffset += pictures.Count;
})
.Repeat()
.TakeWhile(pictureSet => pictureSet.Pictures.Count > 0);
});
}
private async Task<IList<Picture>> GetPageAsync(int offset)
{
var data = await BoringWebServiceCallAsync(offset);
result = data.Pictures.ToList();
}
// this version uses Observable.Run() (which just uses Task.Run under the hood)
// in case you cannot convert your
// web service call to be asynchronous
private IObservable<IList<Picture>> GetPageAsync(int offset)
{
return Observable.Run(() =>
{
var result = new List<Picture>();
... boring web service call here
return result;
});
}
}
Clients just need to add a SelectMany call to get their IObservable<Picture>. They can choose to store the pictureSet.NextOffset if they wish.
pictureProvider
.GetPictures()
.SelectMany(pictureSet => pictureSet.Pictures)
.Subscribe(picture => whatever);
Instead of thinking about how to save the subscription state, I would think about how to replay the state of the inputs (i.e. I'd try to create a serializable ReplaySubject that, on resume, would just resubscribe and catch back up to the current state).
How do you force objects to dispose after use in order to free up memory? And, how do you force GC to collect?
Here's my Save Code. I've noticed that, every time I execute this function, my memory consumption goes up that would eventually caused an out of memory error after a couple of hits.
protected void btnSaveEmptyOC_Click(object sender, EventArgs e)
{
try
{
if (ViewState["ServiceDetailID"].ToString() != null)
{
CashExpense tblCashExpenses = new CashExpense();
Guid CashExpensesID = Guid.NewGuid();
tblCashExpenses.CashExpensesID = CashExpensesID;
tblCashExpenses.ServiceDetailsID = new Guid(ViewState["ServiceDetailID"].ToString());
tblCashExpenses.Description = txtDescriptionEmptyOC.Text;
tblCashExpenses.Quantity = Decimal.Parse(txtQTYEmptyOC.Text);
tblCashExpenses.UnitCost = Decimal.Parse(txtUnitCostEmptyOC.Text);
tblCashExpenses.CreatedBy = User.Identity.Name;
tblCashExpenses.DateCreated = DateTime.Now;
tblCashExpenses.CashExpensesTypeID = "OTHER";
CashExpenses_worker.insert(tblCashExpenses);
CashExpenses_worker.submit();
//Clear items after saving
txtDescriptionEmptyOC.Text = "";
txtQTYEmptyOC.Text = "";
txtUnitCostEmptyOC.Text = "";
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOC2, "SaveEmptyOC", this.Page);
MyAuditProvider.Insert(this.GetType().ToString(), ViewState["MarginAnalysisID"].ToString(), MessageCenter.Mode.ADD, MessageCenter.CashExpenseMaintenace.InsertOC2, Page.Request, User);
divOtherCost.Visible = false;
grd_othercost.Visible = true;
btnaddothercost.Visible = true;
tblCashExpenses = null;
}
else
{
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.SaveServiceDetailOC, "SaveEmptyOC", this.Page);
}
}
catch
{
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOCError, "SaveEmptyOC", this.Page);
}
finally
{
//Rebinds the Grid
populategrd_othercost();
Dispose();
GC.SuppressFinalize(this);
}
}
Here's My business layer class
public class CashExpensesBL
{
CEADataStoreDataContext CashExpensesDB = new CEADataStoreDataContext();
public IEnumerable<CashExpense> get()
{
return CashExpensesDB.CashExpenses;
}
public IEnumerable<CashExpense> get(Expression<Func<CashExpense, Boolean>> express)
{
return CashExpensesDB.CashExpenses.Where(express);
}
public void insert(CashExpense item)
{
CashExpensesDB.CashExpenses.InsertOnSubmit(item);
}
public void delete(CashExpense item)
{
CashExpensesDB.CashExpenses.DeleteOnSubmit(item);
}
public void deleteDC(Guid servicedetailid)
{
CashExpensesDB.sp_deleteDefaultCost(servicedetailid);
}
public void submit()
{
CashExpensesDB.SubmitChanges();
}
}
You should dispose your DataContext. I can't see it being removed anywhere, so the connection will remain open and references may be held on to (preventing the GC from picking them up). This may be what's causing the problem. If you don't want to dispose manually, you can perform the transaction within a using block.
Edit in response to Business Layer update -
You can wrap the methods in using blocks like this:
public void insert(CashExpense item)
{
using(CEADataStoreDataContext CashExpensesDB = new CEADataStoreDataContext())
{
CashExpensesDB.CashExpenses.InsertOnSubmit(item);
CashExpensesDB.SubmitChanges();
}
}
Assign nulls to variables referencing your objects, the use GC.Collect(); to force garbage collection. You may need to call it twice in a row to speed non-accessible objects through the process.
Set the object to null, then call:
GC.Collect();
GC.WaitForPendingFinalizers();