If I have a coroutine as follows, will the code in the finally block get called?
public IEnumerator MyCoroutine(int input)
{
try
{
if(input > 10)
{
Console.WriteLine("Can't count that high.");
yield break;
}
Console.WriteLine("Counting:");
for(int i = 0; i < input; i++)
{
Console.WriteLine(i.ToString());
yield return null;
}
}
finally
{
Console.WriteLine("Finally!");
}
}
As long as the iterator/enumerator is disposed properly (
IDisposable.Dispose()is called) then yes:http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
However, be careful that
Dispose()is indeed called, or else you may end up with unintended results at best. For more information on this phenomenon and some gotchas to watch out for, check out this blog post:Yield and usings – your Dispose may not be called!
(Thanks to Scott B for providing the link, placing in the answer since everybody seems to be missing it)
Additionally:
http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx