0

I have ASP.Net MVC project and I am trying to call some methods from System.Speech. In my local all is working as expected but when I'm publishing it in Windows Azure it throws NullReferenceException. This my code which throws exception(in line 9):

1     public async static Task<byte[]> ToSpeech(string text)
2        {
3            byte[] bytes;
4            var stream = new MemoryStream();
5            await Task.Run(() =>
6                    {
7                        using (var speech = new SpeechSynthesizer())
8                        {
9                             speech.SetOutputToWaveStream(stream);
10                            speech.Speak(text);
11                        }
12                    });
13            bytes = ConvertWavToMP3(stream);
14            return bytes;
15        }

This is the thrown exception: enter image description here

Edit1

The problem is in SpeechSynthesizer , In my local when calling SpeechSynthesizer constructor the fields of speech property initializes normally but when I'm debugging the publish version after calling cosntructor they already thrown exception. enter image description here

Narek
  • 459
  • 2
  • 13
  • The issue is that in the guts of the SpeechSynthesizer it's trying to access the registry which isn't available to you in an Azure AppService. If you were on IIS you could set the identity to have those permission and it would probably work. – b.pell Dec 28 '18 at 19:42

1 Answers1

1

That has nothing to do with azure - you can get the same on your computer.

The usage of USING with a task makes no sense. You run the possible condition that your task is queued, and be fore it is executed the using statement exits - invalidating the speed variable.

This is simply bad code.

You must pretty much do all the processing in the run method of the task. That includes creating the synthesizer object. Just pass the string into the run method.

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • Thanks for replying, I agree with you that code is not good, but now problem not is in it, In my local when calling SpeechSynthesizer constructor the fields of speech property initializes normally but when I'm debugging the publish version after calling constructor they already thrown exception. I just edited my question and added screenshot – Narek Jan 10 '16 at 14:46
  • Well, I tell you what the error is. You treat in hard to repro multi thread issues because of lack of fundamentals. Fixing by reorganizing your code is less time than even writing your comment. If you do not want to do it - maybe read a book about multi threaded programming. Your variable is null because that is what is left once the using statement closes it. – TomTom Jan 10 '16 at 15:09
  • You can do better. You do realize that the task may see a non initialized memory stream? – TomTom Jan 10 '16 at 17:23
  • That can't be the reason of this exception! – Narek Jan 10 '16 at 17:27