Is it possible to subscribe to a lib event on a REST request and wait for a return?

I would like to know if it is possible to subscribe to a third party lib event, which in this case is Microsoft.Speech.dll, because in my attempt, it didnt work, that is, the recognition does not happen and the event is not triggered. I tried using Task and without, but nothing. I don’t really know if it’s possible to subscribe to an event that way and the request wait it. Follow the code.

private string text = string.Empty;

public async Task<string> Get()
{
    var result = Task.Run(() =>
    {
        var cmds = new string[] { "cmd 1", "cmd 2", "cmd N" };
        var ci = new CultureInfo("pt-BR");
        var sre = new SpeechRecognitionEngine(ci);
        var g = new Choices();
        g.Add(cmds);
        var gb = new GrammarBuilder(g);
        var g = new Grammar(gb);
        sre.RequestRecognizerUpdate();
        sre.LoadGrammarAsync(g);
        sre.SpeechRecognized += Sre_SpeechRecognized;

        sre.SetInputToWaveFile("anyWavfile.wav");
        sre.RecognizeAsync(RecognizeMode.Multiple);

    });

    await Task.WhenAll(result);

    return text;
}

private void Sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
    text += e.Result.Text;
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Thanks @Michael, but i solved with ManualResetEvent. TaskCompletionSource would be better?

private string text = string.Empty;
private ManualResetEvent manualResetEvent = new ManualResetEvent(false);

public string Get()
{
    var result = Task.Run(() =>
    {
        //code...

    });

    manualResetEvent.WaitOne();   

    return text;
}

private void Sre_RecognizeCompleted(object sender, RecognizeCompletedEventArgs e)
{
    manualResetEvent.Set();
}

private void Sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
    text += e.Result.Text;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x