programing

AsyncCallback이란 무엇입니까?

nasanasas 2020. 10. 23. 07:58
반응형

AsyncCallback이란 무엇입니까?


AsyncCallback의 용도는 무엇이며 왜 사용해야합니까?


경우 async에있어서의 처리를 마친 AsyncCallback후 처리 문이 실행될 수있는 방법은 자동으로 호출된다. 이 기술을 사용하면 async스레드가 완료 될 때까지 폴링하거나 기다릴 필요가 없습니다 .

Async콜백 사용에 대한 추가 설명은 다음과 같습니다 .

콜백 모델 : 콜백 모델에서는 콜백 할 메서드를 지정하고 호출을 완료하기 위해 콜백 메서드에 필요한 모든 상태를 포함해야합니다. 콜백 모델은 다음 예제에서 볼 수 있습니다.

static byte[] buffer = new byte[100];

static void TestCallbackAPM()
{
    string filename = System.IO.Path.Combine (System.Environment.CurrentDirectory, "mfc71.pdb");

    FileStream strm = new FileStream(filename,
        FileMode.Open, FileAccess.Read, FileShare.Read, 1024,
        FileOptions.Asynchronous);

    // Make the asynchronous call
    IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length,
        new AsyncCallback(CompleteRead), strm);
}

이 모델에서는 AsyncCallback작업이 완료 될 때 다른 스레드에서 호출 할 메서드를 지정 하여 새 대리자를 만듭니다 . 또한 호출 상태로 필요할 수있는 일부 개체를 지정하고 있습니다. 이 예제에서는 스트림을 호출 EndRead하고 닫아야 하기 때문에 스트림 객체를 전송합니다 .

호출이 끝날 때 호출되도록 생성하는 메서드는 다음과 같습니다.

static void CompleteRead(IAsyncResult result)
{
    Console.WriteLine("Read Completed");

    FileStream strm = (FileStream) result.AsyncState;

    // Finished, so we can call EndRead and it will return without blocking
    int numBytes = strm.EndRead(result);

    // Don't forget to close the stream
    strm.Close();

    Console.WriteLine("Read {0} Bytes", numBytes);
    Console.WriteLine(BitConverter.ToString(buffer));
}

다른 기술로는 Wait-until-donePolling이 있습니다.

완료 될 때까지 대기 모델 완료 될 때까지 대기 모델을 사용하면 비동기 호출을 시작하고 다른 작업을 수행 할 수 있습니다. 다른 작업이 완료되면 호출 종료를 시도 할 수 있으며 비동기 호출이 완료 될 때까지 차단됩니다.

// Make the asynchronous call
strm.Read(buffer, 0, buffer.Length);
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);

// Do some work here while you wait

// Calling EndRead will block until the Async work is complete
int numBytes = strm.EndRead(result);

또는 대기 핸들을 사용할 수 있습니다.

result.AsyncWaitHandle.WaitOne();

폴링 모델 폴링 방법은 코드가를 폴링하여 IAsyncResult완료 여부를 확인 한다는 점을 제외하면 비슷 합니다.

// Make the asynchronous call
IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, null, null);

// Poll testing to see if complete
while (!result.IsCompleted)
{
    // Do more work here if the call isn't complete
    Thread.Sleep(100);
}

이렇게 생각해보세요. 병렬로 실행하려는 몇 가지 작업이 있습니다. 비동기 적으로 실행되는 스레드를 사용하여이를 활성화 할 수 있습니다. 이것은 화재 및 잊기 메커니즘입니다.

그러나 일부 상황에서는 실행하고 잊을 수 있지만 작업이 완료되면 알림이 필요한 메커니즘이 필요합니다. 이를 위해 비동기 콜백을 사용합니다.

작업은 비동기 적이지만 작업이 완료되면 다시 호출합니다. 이것의 장점은 작업이 완료 될 때까지 기다릴 필요가 없다는 것입니다. 다른 작업을 자유롭게 실행할 수 있으므로 스레드가 차단되지 않습니다.

An example of this would be a background transfer of a large file. While the transfer is in progress you dont really want to block the user from doing other operations. Once the transfer is complete the process will call you back on an async method, where you can probably pop up a message box which says 'Transfer complete'


AsyncCallbacks are used to specify a function to call when an asynchronous operation is completed. For example, if you were doing an IO operation you would call BeginRead on a stream and pass in an AsyncCAllback delegate. The function would be called when the read operation completed.

For more information see:

참고URL : https://stackoverflow.com/questions/1047662/what-is-asynccallback

반응형