I'm trying to run some code in a new thread because I'm noticing a slowness on my device. It is compiling ok but at the app starting, it freezes and terminates with the message (MyApp is presenting errors constantly).
What I'm doing wrong?
using System.Threading.Tasks;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace MyApp
{
public partial class App : Application
{
public App()
{
InitializeComponent();
}
protected override void OnStart()
{
new System.Threading.Thread(new System.Threading.ThreadStart(() => {
TestaLogin();
})).Start();
}
private void TestaLogin()
{
try
{
Context mContext = Android.App.Application.Context;
ISharedPreferences pref = PreferenceManager.GetDefaultSharedPreferences(mContext);
string uid = pref.GetString("uid", "0");
string token = pref.GetString("token", "0");
if (uid == "0" || token == "0")
{
Device.BeginInvokeOnMainThread(() => { MainPage = new Login(); });
}
else
{
if (Logar(uid, token))
Device.BeginInvokeOnMainThread(() => { MainPage = new MainPage(uid); });
else
Device.BeginInvokeOnMainThread(() => { MainPage = new Login(); });
}
}
catch (Exception e)
{
throw e;
}
}
private bool Logar(string user, string pass)
{
try
{
using (WebClient client = new WebClient())
{
return client.DownloadString("https://www.example.com/mobile/login.php?u=" + user + "&t=" + pass) == "0" ? false : true;
}
}
catch
{
return false;
}
}
}
}
I also wanted to know if lines like this has to be inside the MainThread, I thought that because it's handling changing the page:
Device.BeginInvokeOnMainThread(() => { MainPage = new MainPage(uid); });