다음을 통해 공유


FileStream.BeginWrite 메서드

비동기 쓰기 작업을 시작합니다.

네임스페이스: System.IO
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
Public Overrides Function BeginWrite ( _
    array As Byte(), _
    offset As Integer, _
    numBytes As Integer, _
    userCallback As AsyncCallback, _
    stateObject As Object _
) As IAsyncResult
‘사용 방법
Dim instance As FileStream
Dim array As Byte()
Dim offset As Integer
Dim numBytes As Integer
Dim userCallback As AsyncCallback
Dim stateObject As Object
Dim returnValue As IAsyncResult

returnValue = instance.BeginWrite(array, offset, numBytes, userCallback, stateObject)
public override IAsyncResult BeginWrite (
    byte[] array,
    int offset,
    int numBytes,
    AsyncCallback userCallback,
    Object stateObject
)
public:
virtual IAsyncResult^ BeginWrite (
    array<unsigned char>^ array, 
    int offset, 
    int numBytes, 
    AsyncCallback^ userCallback, 
    Object^ stateObject
) override
public IAsyncResult BeginWrite (
    byte[] array, 
    int offset, 
    int numBytes, 
    AsyncCallback userCallback, 
    Object stateObject
)
public override function BeginWrite (
    array : byte[], 
    offset : int, 
    numBytes : int, 
    userCallback : AsyncCallback, 
    stateObject : Object
) : IAsyncResult

매개 변수

  • array
    현재 스트림에 쓸 데이터를 포함하는 버퍼입니다.
  • offset
    현재 스트림으로 바이트를 복사하기 시작할 array의 바이트 오프셋(0부터 시작)입니다.
  • numBytes
    쓸 최대 바이트 수입니다.
  • userCallback
    비동기 쓰기 작업이 완료되면 호출될 메서드입니다.
  • stateObject
    다른 요청에서 특정 비동기 쓰기 요청을 구별하는 사용자 제공 개체입니다.

반환 값

비동기 쓰기를 참조하는 IAsyncResult입니다.

예외

예외 형식 조건

ArgumentException

array 길이에서 offset을 빼면 numBytes보다 작은 경우

ArgumentNullException

array가 Null 참조(Visual Basic의 경우 Nothing)인 경우

ArgumentOutOfRangeException

offset 또는 numBytes가 음수인 경우

NotSupportedException

스트림이 쓰기를 지원하지 않는 경우

ObjectDisposedException

스트림이 닫혀 있는 경우

IOException

I/O 오류가 발생하는 경우

설명

EndWriteBeginWrite에서 각 IAsyncResult에 대해 한 번씩 호출해야 합니다. EndWrite는 I/O 작업이 완료될 때까지 차단됩니다.

이 메서드는 BeginWrite를 재정의합니다.

FileStream은 동기 I/O와 비동기 I/O의 서로 다른 두 가지 작업 모드를 제공하지만 내부 운영 체제 리소스에서는 이 모드 중 하나에서만 액세스할 수 있는 경우도 있습니다. 기본적으로 FileStream은 운영 체제 핸들을 동기적으로 열기 때문에 Windows에서 비동기 메서드의 속도가 저하됩니다. 비동기 메서드가 사용되면, FileStream(String,FileMode,FileAccess,FileShare,Int32,Boolean) 생성자를 사용하십시오.

스트림이 닫혀 있거나 잘못된 인수를 전달하는 경우 BeginWrite에서 즉시 예외가 throw됩니다. IO 요청 중에 발생하는 디스크 오류 같이 비동기 쓰기 요청 중에 발생하는 오류는 스레드 풀 스레드에서 발생하고 EndWrite를 호출하면 표시됩니다.

참고

Windows에서는 64KB 미만의 모든 I/O 작업은 성능 향상을 위해 동기적으로 완료됩니다. 비동기 I/O는 버퍼 크기가 64KB 미만인 경우 성능을 저하시킬 수 있습니다.

읽은 바이트 수를 확인하려면 IAsyncResult를 사용하여 EndWrite를 호출해야 합니다.

비동기 요청을 동시에 여러 번 시도하면 요청 완료 순서가 불확실해집니다.

다음 표에서는 일반적인 예 또는 관련된 I/O 작업의 예를 보여 줍니다.

수행 작업

참조 항목

텍스트 파일을 만듭니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에 씁니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에서 읽습니다.

방법: 파일의 텍스트 읽기

파일에 텍스트를 추가합니다.

방법: 로그 파일 열기 및 추가

File.AppendText

FileInfo.AppendText

파일 이름을 바꾸거나 이동합니다.

File.Move

FileInfo.MoveTo

파일을 복사합니다.

File.Copy

FileInfo.CopyTo

파일 크기를 가져옵니다.

FileInfo.Length

파일 특성을 가져옵니다.

File.GetAttributes

파일의 특성을 설정합니다.

File.SetAttributes

파일이 있는지 여부를 확인합니다.

File.Exists

이진 파일에서 읽습니다.

방법: 새로 만든 데이터 파일 읽기 및 쓰기

이진 파일에 씁니다.

방법: 새로 만든 데이터 파일 읽기 및 쓰기

디렉터리를 만듭니다.

Directory.CreateDirectory

Directory.CreateDirectory

예제

이 코드 예제는 FileStream(String,FileMode,FileAccess,FileShare,Int32,Boolean) 생성자에 대해 제공되는 보다 큰 예제의 일부입니다.

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
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);
}
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 );
}
public static void main(String[] args)
{
    // Create a synchronization object that gets 
    // signaled when verification is complete.
    ManualResetEvent manualEvent = new ManualResetEvent(false);

    // Create random data to write to the file.
    ubyte writeArray[] = new ubyte[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.get_IsAsync()) ? "" : "not ");
    FStream classfStream = new FStream();

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

    // Concurrently do other work and then wait 
    // for the data to be written and verified.
    manualEvent.WaitOne(5000, false);
} //main

플랫폼

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

FileStream 클래스
FileStream 멤버
System.IO 네임스페이스

기타 리소스

파일 및 스트림 I/O
방법: 파일의 텍스트 읽기
방법: 파일에 텍스트 쓰기
비동기 파일 I/O