Link to Snippet

Resource cleanup event combinator

Declares an event combinator 'Event.using' that automatically releases resources allocated by a previous event occurence. Each event occurence creates a value using a function specified by the user and automatically calls 'Dispose' when generating a new value.

openSystemmoduleEvent=/// Generates new values using the specified function 'f' (just like/// 'Event.map'), but automatically diposes of the previous value when /// a new value is generated.letusingfevt=evt|>Event.scan (funstinp->// Dipose of the previous value if it is not 'null'ifst<>Unchecked.defaultof<_>then
(st:>IDisposable).Dispose()
finp ) Unchecked.defaultof<_>

openSystem.DrawingopenSystem.Windows.Formsletcolors=(...)letfrm=(...)// Turns colors into brushes, but automatically disposes // of the previous brush when creating a new onecolors|>Event.using (funclr->newSolidBrush(clr))
|>Event.add (funbr->frm.BackBrush<-br)