2012-04-19 52 views
2

在用JS編寫的Windows 8 Metro應用程序中,我打開一個文件,獲取流,使用'promise - .then'模式向其中寫入一些圖像數據。它工作正常 - 文件已成功保存到文件系統,除了在使用BitmapEncoder刷新文件流之後,流仍處於打開狀態。即;在我殺死應用程序之前我無法訪問該文件,但'流'變量超出了我的引用範圍,所以我無法關閉它()。是否有可與C#使用語句相媲美的東西?在WinJS Metro應用程序中使用BitmapEncoder後關閉流

...then(function (file) { 
       return file.openAsync(Windows.Storage.FileAccessMode.readWrite); 
      }) 
.then(function (stream) { 
       //Create imageencoder object 
       return Imaging.BitmapEncoder.createAsync(Imaging.BitmapEncoder.pngEncoderId, stream); 
      }) 
.then(function (encoder) { 
       //Set the pixel data in the encoder ('canvasImage.data' is an existing image stream) 
       encoder.setPixelData(Imaging.BitmapPixelFormat.rgba8, Imaging.BitmapAlphaMode.straight, canvasImage.width, canvasImage.height, 96, 96, canvasImage.data); 
       //Go do the encoding 
       return encoder.flushAsync(); 
       //file saved successfully, 
       //but stream is still open and the stream variable is out of scope. 
      }; 

回答

1

來自Microsoft的simple imaging sample可能會對您有所幫助。下面複製。

在你的情況下,你需要在調用then調用鏈之前聲明流,確保你的名字不會與你的參數碰撞到接受流的函數中(注意它們所在的部分_stream = stream),並添加一個then調用來關閉流。

function scenario2GetImageRotationAsync(file) { 
    var accessMode = Windows.Storage.FileAccessMode.read; 

    // Keep data in-scope across multiple asynchronous methods 
    var stream; 
    var exifRotation; 
    return file.openAsync(accessMode).then(function (_stream) { 
     stream = _stream; 
     return Imaging.BitmapDecoder.createAsync(stream); 
    }).then(function (decoder) { 
     // irrelevant stuff to this question 
    }).then(function() { 
     if (stream) { 
      stream.close(); 
     } 
     return exifRotation; 
    }); 
} 
+0

看來,如果在第一個或第二個'then>的任何地方拋出錯誤,它將使流關閉代碼不執行。最後'then'應該有關閉流的錯誤處理程序。 – 2015-07-07 17:25:09