问题
I'm trying to get a really simple application running listing google Task. I have a SQLite local db I'd like to sync / try syncing at regular interval with Google's server.
I was thinking of simply running a simple background thread so it'd work easily on all devices.
Problem comes down creating that background thread in a PCL project (Xamarin.Forms) I can't seem to find a proper way of making one.
Currently I just have a second thread running as such:
private bool Sync() { //Does stuffs }
private void SynchronizeData()
{
// Repeats sync process every 35s
Device.StartTimer (new TimeSpan (0, 0, 35), Sync);
}
// Is called pretty much when app starts.
private void StartSynchronizationThread()
{
Task.Factory.StartNew(SynchronizeData,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
While it should anyway not be much of a problem considering operation count is really low (worst case for testing purpose it'd be less than a sec blocking) i experience a massive freeze of my application around when thread should be ran first. (Timer expiring for the first time) The freeze last for a good minute...
Once it hapenned, i can stay on the app mostly forever without a single issue. I noticed the following appears quite later though:
[art] Thread[2,tid=2532,WaitingInMainSignalCatcherLoop,Thread*=0xee170800,peer=0x12c00080,"Signal Catcher"]: reacting to signal 3 [art] Wrote stack traces to '/data/anr/traces.txt' [art] Wrote stack traces to '/data/anr/traces.txt' [art] Thread[2,tid=2532,WaitingInMainSignalCatcherLoop,Thread*=0xee170800,peer=0x12c00080,"Signal Catcher"]: reacting to signal 3 [art] Wrote stack traces to '/data/anr/traces.txt'
Traces aren't really giving me much more informations though... But it probably have to do with it.
As anyone a hint regarding this matter ? Package, code example or anything ? Hopefully I missed out on something big e;
Thanks.
回答1:
Working like a charm on an actual device, the issue was linked to the emulator. (Haven't found a fix for it though)
回答2:
In Xamarin forms you have to go native for a proper background task, as described here: Backgrounding with Xamarin Forms
To go native you need to use the Xamarin MessagingCenter to send messages back and forth to an appropriate background task (depending on what you're trying to achieve). For example, defining a service in Android:
[Service]
class YourService : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
// Do your thang!
}
}
来源:https://stackoverflow.com/questions/28566661/xamarin-forms-background-thread