0

I already know you can't normally do this but here's my situation:

I have a non-static List<T> that gets added to during normal use, and then dumped to a database at an interval. I want to be able to use AppDomain.CurrentDomain.ProcessExit in order to dump any values in my List<T> that haven't been dumped yet. The List is cleared each time it is dumped.

Is there any way I can access this List without the given context even though it is static -> not-static?

3
  • No. But if you can get access to the instance variables then you can access the data. Ultimately everything is within some context and with the right designs, methods, and APIs you can do what you are trying. Apr 18, 2016 at 20:34
  • Make the handler non-static.
    – SLaks
    Apr 18, 2016 at 20:34
  • @SLaks or make the list static.
    – RoadieRich
    Apr 18, 2016 at 20:37

1 Answer 1

1

Just add your handler as a lambda, in a scope where it has access to your list.

var list = new List<string>()
{
    "Item 1",
    "Item 2"
};

AppDomain.CurrentDomain.ProcessExit += (sender, theArgs) =>
{
    File.WriteAllLines(@"C:\temp\mylist.txt", list);
};

One nice way would be to encapsulate this behaviour inside a subclass of List<T>.

public class MyReallyPersistentList<T> : List<T>
{
    public MyReallyPersistentList()
    {
        AppDomain.CurrentDomain.ProcessExit += (sender, args) => 
        {
            var items = this.Select(i => i?.ToString());
            File.AppendAllLines(@"C:\temp\mylist.txt", items);
        };
    }
}
3
  • so i can set the handler for ProcessExit even though Application.Run() has already been executed?
    – 5SK5
    Apr 18, 2016 at 20:47
  • You never mentioned Application.Run before. Is this a WinForms application? I don't see why it would matter though - you can add a ProcessExit handler any time before your process exits (obviously not after!!)
    – RB.
    Apr 18, 2016 at 20:49
  • Well, whatever you are using, you are aiming to add the ProcessExit handler just after you create the list. As I say, encapsulating this logic inside a subclass of List is the easiest and safest (and most self-documenting) way to do it.
    – RB.
    Apr 18, 2016 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.