FileStream.IsAsync Свойство

Определение

Получает значение, указывающее, как был открыт FileStream: синхронно или асинхронно.

public:
 virtual property bool IsAsync { bool get(); };
public virtual bool IsAsync { get; }
member this.IsAsync : bool
Public Overridable ReadOnly Property IsAsync As Boolean

Значение свойства

Значение true, если FileStream был открыт асинхронно, в противном случае — значение false.

Примеры

Этот пример кода является частью более крупного примера, предоставленного для конструктора FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) .

int main()
{
   
   // Create a synchronization object that gets 
   // signaled when verification is complete.
   ManualResetEvent^ manualEvent = gcnew ManualResetEvent( false );
   
   // Create the data to write to the file.
   array<Byte>^writeArray = gcnew array<Byte>(100000);
   (gcnew Random)->NextBytes( writeArray );
   FileStream^ fStream = gcnew FileStream(  "Test#@@#.dat",FileMode::Create,FileAccess::ReadWrite,FileShare::None,4096,true );
   
   // Check that the FileStream was opened asynchronously.
   Console::WriteLine( "fStream was {0}opened asynchronously.", fStream->IsAsync ? (String^)"" : "not " );
   
   // Asynchronously write to the file.
   IAsyncResult^ asyncResult = fStream->BeginWrite( writeArray, 0, writeArray->Length, gcnew AsyncCallback( &FStream::EndWriteCallback ), gcnew State( fStream,writeArray,manualEvent ) );
   
   // Concurrently do other work and then wait 
   // for the data to be written and verified.
   manualEvent->WaitOne( 5000, false );
}
static void Main()
{
    // Create a synchronization object that gets
    // signaled when verification is complete.
    ManualResetEvent manualEvent = new ManualResetEvent(false);

    // Create random data to write to the file.
    byte[] writeArray = new byte[100000];
    new Random().NextBytes(writeArray);

    FileStream fStream =
        new FileStream("Test#@@#.dat", FileMode.Create,
        FileAccess.ReadWrite, FileShare.None, 4096, true);

    // Check that the FileStream was opened asynchronously.
    Console.WriteLine("fStream was {0}opened asynchronously.",
        fStream.IsAsync ? "" : "not ");

    // Asynchronously write to the file.
    IAsyncResult asyncResult = fStream.BeginWrite(
        writeArray, 0, writeArray.Length,
        new AsyncCallback(EndWriteCallback),
        new State(fStream, writeArray, manualEvent));

    // Concurrently do other work and then wait
    // for the data to be written and verified.
    manualEvent.WaitOne(5000, false);
}
// Create a synchronization object that gets
// signaled when verification is complete.
let manualEvent = new ManualResetEvent false

// Create random data to write to the file.
let writeArray = Array.zeroCreate 100000
Random.Shared.NextBytes writeArray

let fStream =
    new FileStream("Test#@@#.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true)

// Check that the FileStream was opened asynchronously.

if fStream.IsAsync then "" else "not "
|> printfn "fStream was %sopened asynchronously."

// Asynchronously write to the file.
let asyncResult =
    fStream.BeginWrite(
        writeArray,
        0,
        writeArray.Length,
        AsyncCallback endWriteCallback,
        State(fStream, writeArray, manualEvent)
    )

// Concurrently do other work and then wait
// for the data to be written and verified.
manualEvent.WaitOne(5000, false) |> ignore
Shared Sub Main()

    ' Create a synchronization object that gets 
    ' signaled when verification is complete.
    Dim manualEvent As New ManualResetEvent(False)

    ' Create random data to write to the file.
    Dim writeArray(100000) As Byte
    Dim randomGenerator As New Random()
    randomGenerator.NextBytes(writeArray)

    Dim fStream As New FileStream("Test#@@#.dat", _
        FileMode.Create, FileAccess.ReadWrite, _
        FileShare.None, 4096, True)

    ' Check that the FileStream was opened asynchronously.
    If fStream.IsAsync = True
        Console.WriteLine("fStream was opened asynchronously.")
    Else
        Console.WriteLine("fStream was not opened asynchronously.")
    End If

    ' Asynchronously write to the file.
    Dim asyncResult As IAsyncResult = fStream.BeginWrite( _
        writeArray, 0, writeArray.Length, _
        AddressOf EndWriteCallback , _
        New State(fStream, writeArray, manualEvent))

    ' Concurrently do other work and then wait
    ' for the data to be written and verified.
    manualEvent.WaitOne(5000, False)
End Sub

Комментарии

Свойство IsAsync определяет, был ли дескриптор FileStream открыт асинхронно, что позволяет коду правильно использовать Handle свойство . В Win32 значение true означает, IsAsync что дескриптор был открыт для перекрывающихся операций ввода-вывода и, следовательно, требует различных параметров для ReadFile и WriteFile.

Это значение указывается при создании экземпляра FileStream класса с помощью конструктора с параметром isAsync, useAsyncили options . Если свойство имеет значение true, поток использует перекрывающиеся операции ввода-вывода для асинхронного выполнения операций с файлами. Однако IsAsync свойство не обязательно должно быть true для вызова ReadAsyncметода , WriteAsyncили CopyToAsync . IsAsync Если свойство имеет значение false и вы вызываете асинхронные операции чтения и записи, поток пользовательского интерфейса по-прежнему не блокируется, но фактическая операция ввода-вывода выполняется синхронно.

Применяется к

См. также раздел