Удалите объект, который используется в конструкторе другого объекта - PullRequest
1 голос
/ 06 февраля 2012

Я использую этот код для чтения значений из изолированного хранилища.

        IsolatedStorageFile isoStore = null;
        StreamReader reader = null;
        IsolatedStorageFileStream isolatedStorageFileStream = null;
        String strIsolatedStorageValue = string.Empty;

        isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);

        try
        {
            isolatedStorageFileStream = new IsolatedStorageFileStream(strKey + ".txt", FileMode.OpenOrCreate, isoStore);
            // This code opens the store and reads the string.
            reader = new StreamReader(isolatedStorageFileStream);

            // Read a line from the file and add it to sb.
            strIsolatedStorageValue = reader.ReadLine();
        }
        catch (Exception)
        {

        }
        finally
        {
            if (isolatedStorageFileStream != null)
            {
                isolatedStorageFileStream.Dispose();
            }
            if (reader != null)
            {
                reader.Dispose();
            }
        }

        // Return the string.
        return strIsolatedStorageValue;

Проблема заключается в том, что когда я удаляю IsolatedStorageFileStream, а затем освобождаю читателя, Visual Studio сообщает мне, что isolatedStorageFileStream может быть удален болееодин раз!и когда я не утилизирую его, я получаю предупреждение о том, что сначала должен быть утилизирован IsolatedStorageFileStream.

Что делать в таком случае, если утилизировать объект, используемый в конструкторе другого одноразового объекта

Спасибо

Ответы [ 3 ]

1 голос
/ 06 февраля 2012

Вы должны располагать программу чтения перед потоком файлов.

Чтобы упростить ваш код, вы должны использовать блоки using.Они автоматически делают для вас шаблон try / finally / dispose:

using (isolatedStorageFileStream = new IsolatedStorageFileStream(
          strKey + ".txt", FileMode.OpenOrCreate, isoStore)) {
    // This code opens the store and reads the string.
    using (reader = new StreamReader(isolatedStorageFileStream)) {
        strIsolatedStorageValue = reader.ReadLine();
   }
}
1 голос
/ 06 февраля 2012

Оператор using автоматически выполняет попытку завершения для IDisposable (утилизируйте, если не ноль) для вас.

using (IsolatedStorageFileStream isolatedStorageFileStream = new IsolatedStorageFileStream(strKey + ".txt", FileMode.OpenOrCreate, isoStore))
{
    using (StreamReader reader = new StreamReader(isolatedStorageFileStream))
    {
        string strIsolatedStorageValue = reader.ReadLine();
        return strIsolatedStorageValue;
    }
}
1 голос
/ 06 февраля 2012

Используйте ключевое слово using:

using (IsolatedStorageFileStream isolatedStorageFileStream = 
       new IsolatedStorageFileStream(
            strKey + ".txt", FileMode.OpenOrCreate, isoStore))
using (StreamReader reader = new StreamReader(isolatedStorageFileStream))
{
    // Read a line from the file and add it to sb.
    strIsolatedStorageValue = reader.ReadLine();
}

return strIsolatedStorageValue;

using безопасно звонит вам Dispose, и вам не нужно звонить вручную.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...