Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

Whisper.net - System.Exception: 'Cannot dispose while processing, please use DisposeAsync instead.'

Whisper.NET 사용 시 기본 예제 코드를 그대로,

sandrohanea / whisper.net
; https://github.com/sandrohanea/whisper.net

using var whisperFactory = WhisperFactory.FromPath("ggml-base.bin");

using var processor = whisperFactory.CreateBuilder()
    .WithLanguage("auto")
    .Build();

using var fileStream = File.OpenRead(wavFileName);

await foreach (var result in processor.ProcessAsync(fileStream))
{
    Console.WriteLine($"{result.Start}->{result.End}: {result.Text}");
}

사용하는 경우, 가령 위의 예제 코드에서 ProcessAsync 후 중간에 탈출해 버리면,

await foreach (var result in processor.ProcessAsync(fileStream))
{
    Console.WriteLine($"{result.Start}->{result.End}: {result.Text}");
	break; // 중간에 탈출
}

"Cannot dispose while processing, please use DisposeAsync instead."라는 예외가 발생합니다.

Unhandled exception. System.Exception: Cannot dispose while processing, please use DisposeAsync instead.
   at Whisper.net.WhisperProcessor.Dispose()
   at Program.Main(String[] args)
   at Program.<Main>(String[] args)

처음엔 저 오류가 BCL(.NET 기본 라이브러리)에서 발생하는 줄 알고 다소 헤맸는데요, 실제로는 Whisper.NET 내에서 생성한 예외였습니다. 잠시 살펴볼까요? ^^

우선, 오류 메시지에서 알 수 있듯이, Dispose에서 발생하는 건데요,

public void Dispose()
{
    if (processingSemaphore.CurrentCount == 0)
    {
    	throw new Exception("Cannot dispose while processing, please use DisposeAsync instead.");
    }
    // ...[생략]...
}

조건은 세마포어가 0일 때이고, 이와 관련된 소스 코드를 보면,

internal WhisperProcessor(WhisperProcessorOptions options, INativeWhisper nativeWhisper)
{
    this.options = options;
    this.nativeWhisper = nativeWhisper;
    myId = Interlocked.Increment(ref currentProcessorId);
    processorInstances[myId] = this;
    currentWhisperContext = options.ContextHandle;
    whisperParams = GetWhisperParams();
    processingSemaphore = new SemaphoreSlim(1);
}

public unsafe void Process(ReadOnlySpan<float> samples)
{
    if (isDisposed)
    {
        throw new ObjectDisposedException("This processor has already been disposed.");
    }
    fixed (float* samples2 = samples)
    {
        nint whisperState = GetWhisperState();
        try
        {
            processingSemaphore.Wait();
            segmentIndex = 0;
            nativeWhisper.Whisper_Full_With_State(currentWhisperContext, whisperState, whisperParams, (nint)samples2, samples.Length);
        }
        finally
        {
            nativeWhisper.Whisper_Free_State(whisperState);
            processingSemaphore.Release();
        }
    }
}

음성 인식을 하는 단계에서 세마포어를 획득/해제하고 있는데, 따라서 만약 비동기 호출로 세마포어가 아직 해제되지 않고 있는 상태에서 Dispose가 호출되면 예외가 발생하는 것입니다.




문제의 해결 방법은, 예외 메시지에서 친절하게 알려주고 있는 것처럼 동기 방식의 Dispose가 아닌 IAsyncDisposable 방식의 DisposeAsync를 사용하면 됩니다. 이를 위해 소스 코드에서는 using var ... 코드에 await을 추가해 주면 됩니다.

await using var processor = whisperFactory.CreateBuilder()
    .WithLanguage("auto")
    .Build();

혹은, 원론적으로 try ... finally 구문으로 풀어낸 후 finally에서 DisposeAsync를 호출해도 됩니다.

WhisperProcessor? processor = whisperFactory.CreateBuilder()
    .WithLanguage("auto")
    .Build();

try
{
    await foreach (var result in processor.ProcessAsync(wavStream))
    {
        Console.WriteLine($"{result.Start}->{result.End}: {result.Text}");
        break;
    }
}
finally
{
    await processor.DisposeAsync();
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 10/14/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 166  167  168  169  170  171  172  173  174  175  176  177  [178]  179  180  ...
NoWriterDateCnt.TitleFile(s)
658정성태2/1/200931482Team Foundation Server: 30. 소스 서버 보안
657정성태2/1/200934665Windows: 40. Q1 Ultra + Windows 7 베타
656정성태2/1/200935677디버깅 기술: 24. .NET JIT 최적화 코드 생성 제어
655정성태1/31/200932442Windows: 39. IE8 표준 모드 [4]
653정성태1/29/200927271.NET Framework: 122. XML Serializer를 이용한 값 복사: 성능은 어떨까!파일 다운로드1
652정성태1/22/200928007.NET Framework: 121. WPF - PrintTicket provider failed to bind to printer.
651정성태1/20/200925581.NET Framework: 120. 타입이 다른 배열끼리의 변환
650정성태1/19/200937538COM 개체 관련: 21. C/C++ 프로젝트에 /clr 옵션 적용으로 인한 COM 개체 사용 오류
649정성태1/18/200934919Windows: 38. Q1U UMPC에 Windows 7 베타 설치하기
648정성태1/18/200932776Windows: 37. Windows PE를 USB 메모리에 적용
647정성태1/18/200943567Windows: 36. Windows PE ISO 이미지 만들기 [1]
646정성태1/18/200936692디버깅 기술: 23. COMPLUS_ZapDisable - JIT 최적화 코드 생성 제어 [1]
645정성태1/11/200935469Windows: 35. 서명되지 않은 드라이버 로딩 방법
644정성태1/11/200926321Windows: 34. VPC 설치 후기 [2]
643정성태1/10/200931468Windows: 33. Windows 7 베타와 VMA 충돌 [1]
642정성태1/8/200929997개발 환경 구성: 34. Sysinternals의 모든 툴을 한번에 업데이트 하는 방법 [1]
641정성태1/7/200927094기타: 27. D820 - A09 바이오스 업데이트 프로그램 패치 [2]
640정성태1/4/200929084Team Foundation Server: 29. ClickOnce 응용 프로그램 배포를 Team Build에 추가.
639정성태1/4/200927077Team Foundation Server: 28. PFX 코드 서명을 포함한 프로젝트의 팀 빌드 실패 - MSB4018
638정성태1/3/200930044.NET Framework: 119. WPF - 의존 속성 정의에서 XamlParseException 발생하는 예 [2]
637정성태1/1/200932626기타: 26. 2008년 인기 순위 정리
636정성태12/31/200827678.NET Framework: 118. 2진 검색을 이용한 리스트 정렬 삽입파일 다운로드1
635정성태12/29/200830517오류 유형: 66. 파일 암호화 오류 - Recovery policy configured for this system contains invalid recovery certificate
634정성태12/29/200844708기타: 25. 가상 키보드 관련 정리 [4]
633정성태12/20/200833479기타: 24. RMClock for x64 [3]
632정성태12/19/200839155기타: 23. D820 - 배터리 없이 바이오스 업데이트 방법 [2]파일 다운로드1
... 166  167  168  169  170  171  172  173  174  175  176  177  [178]  179  180  ...