2017-02-15 10 views
0

Мое приложение разбивается, когда я вызываю функцию Print, пока я использую System.Timers.ElapsedEventHandler(checkForMessage).C# Android Xamarin - сбой при использовании TextView.Text с ElapsedEventHandler

Я назвал функцию Print в других контекстах, и проблем не возникло.

using System; 
using Android.App; 
using Android.Widget; 
using Android.OS; 

namespace Ev3BtCom 
{ 
    [Activity(Label = "Ev3BtCom", MainLauncher = true, Icon = "@drawable/icon")] 
    public class MainActivity : Activity 
    { 
     Ev3Messaging _ev3Messaging = new Ev3Messaging(); 

     bool isParsing = true; 
     TextView infosLabel; 

     protected override void OnCreate(Bundle bundle) 
     { 
      base.OnCreate(bundle); 

      SetContentView (Resource.Layout.Main); 

      ... 
      infosLabel = FindViewById<TextView>(Resource.Id.Infos); 

      _ev3Messaging = new Ev3Messaging(); 


      System.Timers.Timer checkForTime = new System.Timers.Timer(500); 
      checkForTime.Elapsed += new System.Timers.ElapsedEventHandler(checkForMessage); 
      checkForTime.Enabled = true; 



      connectBut.Click += async (object sender, EventArgs e) => 
      { 
       bool error = false; 
       try 
       { 
        await _ev3Messaging.Connect(brickNameET.Text); 
       } 
       catch (Exception ex) 
       { 
        Print(ex.Message); 
        error = true; 
       } 
       if(!error) 
       { 
        Print("Connected"); 
        isParsing = false; 
       } 
      }; 

      ...//Many use of the print function in the same context WITHOUT CRASH 
     } 

     async void checkForMessage(object source, System.Timers.ElapsedEventArgs e) 
     { 
      if (!isParsing) 
      { 
       isParsing = true; 
       byte[] datas = new byte[0]; 
       try 
       { 
        datas = await _ev3Messaging.ReceiveText(); 
       }catch (Exception ex) 
       { 
        await _ev3Messaging.SendText("Text", ex.Message); 
        Print(ex.Message); // MAKES APP CRASH 
       } 
       if (datas.Length != 0) 
       { 
        string printedText = "Received: "; 
        foreach (byte b in datas) 
         printedText += (int)b + ","; 
        Print(printedText); // MAKES APP CRASH 
        await _ev3Messaging.SendText("Text", printedText); 
       } 
       Print("Test"); // MAKES APP CRASH 
       isParsing = false; 
      } 
     } 

     void Print(string text) 
     { 
      infosLabel.Text += text + "\n"; // When I remove this line, there is no more crash 
     } 
    } 
} 
+0

Что такое Exception/StackTrace? – SushiHangover

+0

Не отображается Exception, приложение закрыто без какого-либо сообщения ... И, извините, я новичок, и я не знаю, что вы имеете в виду под «StackTrace» ... –

+0

Вы можете найти след в своем ' adb logcat'. –

ответ

0

Timer.Elapsed событие всегда в очереди для выполнения на поток пул потоков, так что вам нужно, чтобы убедиться, что вы обновляете элементы управления пользовательского интерфейса в потоке пользовательского интерфейса. Для этого вы можете использовать метод RunOnUiThread следующим образом:

void Print(string text) 
{ 
    RunOnUiThread(() => infosLabel.Text += text + "\n"); 
} 
+0

Спасибо большое! Это сработало ! Я учусь программировать с Xamarin, и я никогда не слышал о RunOnUiThread раньше ... –

+0

Рад это слышать. Вероятно, вы столкнетесь с множеством неясных проблем, подобных этому в будущем, но не сдавайтесь. Всегда есть разумное объяснение, почему что-то не работает. – hankide