1

Will the variable uiContext go out scope after the event handler return? What does the compiler do behind the scene to make this code work.

private void findButton_Click(object sender, RoutedEventArgs e)
{
    SynchronizationContext uiContext = SynchronizationContext.Current;

    Task.Factory.StartNew(() =>
    {
        string pictures =
            Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
        var folder = new DirectoryInfo(pictures);
        FileInfo[] allFiles =
            folder.GetFiles("*.jpg", SearchOption.AllDirectories);
        FileInfo largest =
            allFiles.OrderByDescending(f => f.Length).FirstOrDefault();

        uiContext.Post(unusedArg =>
        {
            outputTextBox.Text = string.Format("Largest file ({0}MB) is {1}",
                largest.Length / (1024 * 1024), largest.FullName);
        },
        null);
    });
}
Tobsey
  • 3,390
  • 14
  • 24
  • What do you know about garbage collection? – zerkms Aug 09 '13 at 11:50
  • 2
    Object is garbage collected when no code parts are referencing it. This means that `uiContext` will be garbage collected when both, thread and method will exit. To be more exact it will become ready for garbage collection. – Leri Aug 09 '13 at 11:50

1 Answers1

1

.NET uses closures in order to prevent Garbage Collector from deleting the uiContext while it is still required by inner methods, actions etc. (here Task.Factory.StartNew).

See:

More over, the SynchronizationContext is a class and you don't know if new instance is createad when you use Current property or it returns you the existing one. Thus you could be not the only one who have a reference to that instance.

Community
  • 1
  • 1
Ryszard Dżegan
  • 24,366
  • 6
  • 38
  • 56