0

I have a ForegroudService in a Xamarin Projects and evrything goes well unless there is an asynchronous method in the service. I call the ForegroundService's start with buttonEvent

private void Speak(object sender, EventArgs e)
        {
            DependencyService.Get<IHelper>().startService();
        }

In Android i Have this Implementation:

public async Task startService()
        {
            Intent downloadIntent = new Intent(Android.App.Application.Context, typeof(DemoIntentService));
            await Task.Run(() => Android.App.Application.Context.StartForegroundService(downloadIntent));
        }

The Asynchronous Method inside Service:

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {

            return OnStartCommandAsync(intent,flags, startId).Result; 

        }

private async Task<StartCommandResult> OnStartCommandAsync(Intent intent, StartCommandFlags flags, int startId)
        {        
            try
            {
                var speechConfig = SpeechConfig.FromSubscription("xxxx", "xxxx");

                using var recognizer = new Microsoft.CognitiveServices.Speech.SpeechRecognizer(speechConfig);

                string destPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "xx.table");

                var keywordModel = KeywordRecognitionModel.FromFile(destPath);
                using var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
                using var keywordRecognizer = new KeywordRecognizer(audioConfig);

                keywordRecognizer.Recognized += (s, e) =>
                {
                    Console.WriteLine("ciao");
                    StopForeground(StopForegroundFlags.Remove);
                };
                 
                KeywordRecognitionResult result = await keywordRecognizer.RecognizeOnceAsync(keywordModel);

            }
            catch (System.Exception e)
            {

            }


            //// Tells the system to not try to recreate the service after it has been killed.
            return StartCommandResult.NotSticky;
        }

The problem is that when I click the button to start the service and consequently listening, the application UI blocks and then crashes and throws this exception

"ProtocolHandler.ReadThread"  at <unknown> <0xffffffff>
  at (wrapper managed-to-native) System.Threading.Monitor.Monitor_wait (object,int) <0x00012>
  at System.Threading.Monitor.ObjWait (bool,int,object) [0x0002f] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/System.Threading/Monitor.cs:85
  at System.Threading.Monitor.Wait (object,int,bool) [0x0000e] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/threading/monitor.cs:218
  at System.Threading.Monitor.Wait (object) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/threading/monitor.cs:238
  at Xamarin.HotReload.HotReloadAgent.Microsoft.VisualStudio.DesignTools.TapContract.Networking.IDataBridge.ReadMessage () [0x0002f] in d:\a\1\s\Source\Xamarin.HotReload.Agent\HotReloadAgent.cs:341
  at Microsoft.VisualStudio.DesignTools.TapContract.Networking.ProtocolHandler.ReadThread (
) [0x00038] in <adbc029e7768468789cf6ada876dcf06>:0
  at System.Threading.ThreadHelper.ThreadStart_Context (object) [0x00014] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/threading/thread.cs:74
  at System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext,System.Threading.ContextCallback,object,bool) [0x00071] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:968
  at System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext,System.Threading.ContextCallback,object,bool) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:910
  at System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext,System.Threading.ContextCallback,object) [0x0002b] in /Users/builder/jenkins/workspace/archive-mono/2020-02/
android/release/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:899
  at System.Threading.ThreadHelper.ThreadStart () [0x00008] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/threading/thread.cs:111
  at (wrapper runtime-invoke) object.runtime_invoke_void__this__ (object,intptr,intptr,intptr) [0x00061] in <0381c8f952fb47759ee29160e807b17d>:0

"Debugger agent"

Does anyone know how I can separate the service from the main UI thread or how to make the main thread not wait for the service result?

  • 1
    `.Result` will block the thread until the async method returns the result, so it is basically the async method synchronously. You can try to implemented the method with two separate services. One with Service as above and the other which actually does the all work in the background.Please take a look;https://stackoverflow.com/questions/41735277/background-service-error-while-using-as-async-task – Cherry Bu - MSFT Nov 13 '20 at 07:12
  • Thank you so much for the solution. It's working very well! @CherryBu-MSFT – Lorenzo Vettori Nov 15 '20 at 21:52

0 Answers0