Dispose StreamResourceInfo.Stream

笑着哭i 提交于 2019-12-05 07:29:27

The confusion, and I agree it is confusing, comes from the subtle but critical concept of ownership of the stream. In the MSDN examples you can look at them as say "Look, no Dispose, no Close, so I'm not supposed to do that?"

But the simple answer is that somebody has to be responsible for closing the stream. The API you are probably calling:

  • Application.GetResourceStream

returns a StreamResourceInfo that is a primitive container for a stream and an URL. Clearly the StreamResourceInfo does not own the stream. So when you call Application.GetResourceStream you now own the stream that is contained in that StreamResourceInfo and, if you did nothing else with it, you would be responsible for closing it. The Application API transfered ownership of the stream from itself to us by returning it as a value to us.

Now the confusing part comes in when you pass the stream to another entity. Let's take an MSDN example:

// Navigate to xaml page
Uri uri = new Uri("/PageResourceFile.xaml", UriKind.Relative);
StreamResourceInfo info = Application.GetResourceStream(uri);
System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader();
Page page = (Page)reader.LoadAsync(info.Stream);
this.pageFrame.Content = page;

Now in this example there is no Dispose and no Close. But there is a transfer of ownership of the stream from us (the caller) to the XamlReader instance. The stream is no longer our responsibility; we have passed ownership over to someone else. In fact, XamlReader does call Close when it is done with the stream. One mystery solved.

The reason this is so problematic is that the concept of ownership is usually implicit in the documentation and we are supposed to "just figure it out." Hopefully just revisiting th concept of ownership and the fact that it is transferable will make it easier to feel comfortable not calling Close with the security that the new owner will. And even if they don't, it's not our problem anymore!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!