The problem with threads. I'm trying to change the UI part by adding a message to textView5. At compile time, everything is fine. I run the application, on the emulator, you can see that it crashes at the stage where I add the decoded text to textView5. I can not understand what my mistake.
using System; using Android.App; using Android.OS; using Android.Support.V7.App; using Android.Widget; using System.Net.Sockets; using System.Threading; using System.Text; using Android.Support.Design.Widget; using Android; namespace App3 { [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)] public class MainActivity : Activity { TextInputEditText textInputEditText1, textInputEditText2, textInputEditText3; Button button1, button2, button3; static TextView textView3, textView5; static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Thread t = new Thread(new ThreadStart(delegate () { Receiver(); })); static MainActivity mn; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_main); button1 = FindViewById<Button>(Resource.Id.button1); button2 = FindViewById<Button>(Resource.Id.button2); button3 = FindViewById<Button>(Resource.Id.button3); textInputEditText1 = FindViewById<TextInputEditText>(Resource.Id.textInputEditText1); textInputEditText2 = FindViewById<TextInputEditText>(Resource.Id.textInputEditText2); textInputEditText3 = FindViewById<TextInputEditText>(Resource.Id.textInputEditText3); textView3 = FindViewById<TextView>(Resource.Id.textView3); textView5 = FindViewById<TextView>(Resource.Id.textView5); button1.Click += Conn; button2.Click += Sender; button3.Click += Disconn; } public void Conn(object sender, EventArgs e) { string ip_address = textInputEditText1.Text; int port = Convert.ToInt32(textInputEditText2.Text); socket.Connect(ip_address, port); if (socket.Connected) { textView3.Text = "Status: Connected"; button3.Visibility = Android.Views.ViewStates.Visible; t.Start(); } else textView3.Text = "Failed to connect to server"; } public void Disconn(object sender, EventArgs e) { t.Abort(); socket.Send(Encoding.Unicode.GetBytes("_0xcAB2402")); Thread.Sleep(150); socket.Shutdown(SocketShutdown.Both); socket.Disconnect(true); button3.Visibility = Android.Views.ViewStates.Invisible; } public void Sender(object sender, EventArgs e) { byte[] msg = Encoding.Unicode.GetBytes(textInputEditText3.Text); socket.Send(msg, 0, msg.Length, 0); } public static void Receiver() { while (true) { byte[] buffer = new byte[128]; socket.Receive(buffer); mn.RunOnUiThread(() => textView5.Append(Encoding.Unicode.GetString(buffer))); // На этом месте крашит } } } }