Figure1ApmPatterns 類的摘錄
private static void SynchronousPattern() {
using (FileStream fs =
new FileStream(typeof(ApmPatterns).Assembly.Location,
FileMode.Open, FileAccess.Read, FileShare.Read, 8192,
FileOptions.Asynchronous)) {
Byte[] data = new Byte[fs.Length];
Int32 bytesRead = fs.Read(data, 0, data.Length);
ProcessData(data);
}
}
#region APM Pattern with Multiple Methods
private sealed class ApmData {
public FileStream m_fs;
public Byte[] m_data;
}
private static void ApmPatternWithMultipleMethods() {
ApmData apmData = new ApmData();
apmData.m_fs =
new FileStream(typeof(ApmPatterns).Assembly.Location,
FileMode.Open, FileAccess.Read, FileShare.Read, 8192,
FileOptions.Asynchronous);
apmData.m_data = new Byte[apmData.m_fs.Length];
apmData.m_fs.BeginRead(apmData.m_data, 0, apmData.m_data.Length,
ReadCompleted, apmData);
// Method returns after issuing async I/O request
}
private static void ReadCompleted(IAsyncResult result) {
ApmData apmData = (ApmData) result.AsyncState;
Int32 bytesRead = apmData.m_fs.EndRead(result);
ProcessData(apmData.m_data);
apmData.m_fs.Close(); // No 'using'
}
#endregion
private static void ApmPatternWithAnonymousMethod() {
FileStream fs =
new FileStream(typeof(ApmPatterns).Assembly.Location,
FileMode.Open, FileAccess.Read, FileShare.Read, 8192,
FileOptions.Asynchronous);
Byte[] data = new Byte[fs.Length];
fs.BeginRead(data, 0, data.Length, delegate(IAsyncResult result) {
Int32 bytesRead = fs.EndRead(result);
ProcessData(data);
fs.Close(); // No 'using'
}, null);
// Method returns after issuing async I/O request
}
private static void ApmPatternWithLambdaExpression() {
FileStream fs =
new FileStream(typeof(ApmPatterns).Assembly.Location,
FileMode.Open, FileAccess.Read, FileShare.Read, 8192,
FileOptions.Asynchronous);
Byte[] data = new Byte[fs.Length];
fs.BeginRead(data, 0, data.Length, result => {
Int32 bytesRead = fs.EndRead(result);
ProcessData(data);
fs.Close(); // No 'using'
}, null);
// Method returns after issuing async I/O request
}