本文整理汇总了C#中IBackgroundTaskInstance类的典型用法代码示例。如果您正苦于以下问题:C# IBackgroundTaskInstance类的具体用法?C# IBackgroundTaskInstance怎么用?C# IBackgroundTaskInstance使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
IBackgroundTaskInstance类属于命名空间,在下文中一共展示了IBackgroundTaskInstance类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
// Ensure our background task remains running
taskDeferral = taskInstance.GetDeferral();
// Mutex will be used to ensure only one thread at a time is talking to the shield / isolated storage
mutex = new Mutex(false, mutexId);
// Initialize WeatherShield
await shield.BeginAsync();
//Initialise the MCP3008 ADC Chip
mcp3008.Initialize();
// Create a timer-initiated ThreadPool task to read data from I2C
i2cTimer = ThreadPoolTimer.CreatePeriodicTimer(PopulateWeatherData, TimeSpan.FromSeconds(i2cReadIntervalSeconds));
//Create a timer-initiated ThreadPool task to read data from the interrupt handler counting the wind instrument activity
windInterruptSample = ThreadPoolTimer.CreatePeriodicTimer(MeasureWindEventData, TimeSpan.FromSeconds(windInterruptSampleInterval));
// Task cancellation handler, release our deferral there
taskInstance.Canceled += OnCanceled;
//Create the interrupt handler listening to the wind speed pin (13). Triggers the GpioPin.ValueChanged event on that pin
//connected to the anemometer.
shield.WindSpeedPin.ValueChanged += WindSpeedPin_ValueChanged;
//Create the interrupt handler listening to the rain guage pin (26). Triggers the Gpio.ValueChanged event on that pin
//connected to the rain guage.
shield.RainPin.ValueChanged += RainPin_ValueChanged;
}
示例2: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
var updater = new LiveTileScheduler();
await updater.CreateSchedule();
deferral.Complete();
}
示例3: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
try
{
await Log.InfoAsync("Synchronization background task started");
var authenticatedSilently = await SecurityManager.TryAuthenticateSilently();
if (authenticatedSilently)
{
IBackendServiceClient storage = new MobileServiceBackendServiceClient(new SyncHandler(), new EventManager(), new LocalSettingsService());
await storage.InitializeAsync();
await storage.TrySyncAsync();
}
else
{
await Log.WarnAsync("Authentication failed.");
}
await Log.InfoAsync("Synchronization background task completed");
}
catch (Exception ex)
{
await ExceptionHandlingHelper.HandleNonFatalErrorAsync(ex, "Synchronization background task failed.", sendTelemetry: false);
}
finally
{
deferral.Complete();
}
}
示例4: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
deferral = taskInstance.GetDeferral();
Initialize();
Start();
}
示例5: TaskInstance_Canceled
private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
this.SendToForeground(CommunicationConstants.BackgroundTaskStopped);
try
{
ApplicationSettings.BackgroundTaskResumeSongTime.Save(BackgroundMediaPlayer.Current.Position.TotalSeconds);
/*
//save state
ApplicationSettingsHelper.SaveSettingsValue(Constants.CurrentTrack, Playlist.CurrentTrackName);
ApplicationSettingsHelper.SaveSettingsValue(Constants.Position, BackgroundMediaPlayer.Current.Position.ToString());
ApplicationSettingsHelper.SaveSettingsValue(Constants.BackgroundTaskState, Constants.BackgroundTaskCancelled);
ApplicationSettingsHelper.SaveSettingsValue(Constants.AppState, Enum.GetName(typeof(ForegroundAppStatus), foregroundAppState));
backgroundtaskrunning = false;
//unsubscribe event handlers
systemmediatransportcontrol.ButtonPressed -= systemmediatransportcontrol_ButtonPressed;
systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;
Playlist.TrackChanged -= playList_TrackChanged;
//clear objects task cancellation can happen uninterrupted
playlistManager.ClearPlaylist();
playlistManager = null;
*/
this.mediaControls.ButtonPressed -= mediaControls_ButtonPressed;
playlistManager = null;
BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
if (_deferral != null)
_deferral.Complete();
}
示例6: Run
// Completion groups allow us to immediately take action after a set of downloads completes.
// In this sample, the server intentionally replies with an error status for some of the downloads.
// Based on the trigger details, we can determine which of the downloads have failed and try them again
// using a new completion group.
public void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTransferCompletionGroupTriggerDetails details = taskInstance.TriggerDetails
as BackgroundTransferCompletionGroupTriggerDetails;
if (details == null)
{
// This task was not triggered by a completion group.
return;
}
List<DownloadOperation> failedDownloads = new List<DownloadOperation>();
int succeeded = 0;
foreach (DownloadOperation download in details.Downloads)
{
if (IsFailed(download))
{
failedDownloads.Add(download);
}
else
{
succeeded++;
}
}
if (failedDownloads.Count > 0)
{
RetryDownloads(failedDownloads);
}
InvokeSimpleToast(succeeded, failedDownloads.Count);
}
示例7: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
// Connect the Ultrasonic Sensor to digital port 4
IUltrasonicRangerSensor sensor = DeviceFactory.Build.UltraSonicSensor(Pin.DigitalPin4);
// Loop endlessly
while (true)
{
Task.Delay(100).Wait(); //Delay 0.1 second
try
{
// Check the value of the Ultrasonic Sensor
string sensorvalue = sensor.MeasureInCentimeters().ToString();
System.Diagnostics.Debug.WriteLine("Ultrasonic reads " + sensorvalue);
}
catch (Exception ex)
{
// NOTE: There are frequent exceptions of the following:
// WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '.
// This appears to be caused by the rapid frequency of writes to the GPIO
// These are being swallowed here/
// If you want to see the exceptions uncomment the following:
// System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}
示例8: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
deferral = taskInstance.GetDeferral();
InitGPIO();
timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500));
}
示例9: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
// Check the task cost
var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
if (cost == BackgroundWorkCostValue.High)
{
return;
}
// Get the cancel token
var cancel = new System.Threading.CancellationTokenSource();
taskInstance.Canceled += (s, e) =>
{
cancel.Cancel();
cancel.Dispose();
};
// Get deferral
var deferral = taskInstance.GetDeferral();
try
{
// Update Tile with the new xml
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(TileUpdaterTask.w10TileXml);
TileNotification tileNotification = new TileNotification(xmldoc);
TileUpdater tileUpdator = TileUpdateManager.CreateTileUpdaterForApplication();
tileUpdator.Update(tileNotification);
}
finally
{
deferral.Complete();
}
}
示例10: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
IReadOnlyList<GeofenceStateChangeReport> reports = GeofenceMonitor.Current.ReadReports();
foreach (var report in reports)
{
if ((report.NewState != GeofenceState.None) &&
(report.NewState != GeofenceState.Removed))
{
await StatusFile.AddStatusEntry(
report.Geofence.Id,
report.NewState == GeofenceState.Entered ? EntryType.EnteredZone : EntryType.ExitedZone);
}
}
XmlDocument template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
NotificationTemplateHelper.CompleteToastOrTileTemplate(
template,
new string[]
{
"One or more of our fences has been crossed"
},
null);
ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();
notifier.Show(new ToastNotification(template));
deferral.Complete();
}
示例11: OnCanceled
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
_cancelRequested = true;
_cancelReason = reason;
Debug.WriteLine($"Background '{sender.Task.Name}' Cancel Requested...");
}
示例12: Run
/// <remarks>
/// If you start any asynchronous methods here, prevent the task
/// from closing prematurely by using BackgroundTaskDeferral as
/// described in http://aka.ms/backgroundtaskdeferral
/// </remarks>
public async void Run(IBackgroundTaskInstance taskInstance)
{
// This deferral should have an instance reference, if it doesn't... the GC will
// come some day, see that this method is not active anymore and the local variable
// should be removed. Which results in the application being closed.
_deferral = taskInstance.GetDeferral();
var restRouteHandler = new RestRouteHandler();
restRouteHandler.RegisterController<AsyncControllerSample>();
restRouteHandler.RegisterController<FromContentControllerSample>();
restRouteHandler.RegisterController<PerCallControllerSample>();
restRouteHandler.RegisterController<SimpleParameterControllerSample>();
restRouteHandler.RegisterController<SingletonControllerSample>();
restRouteHandler.RegisterController<ThrowExceptionControllerSample>();
restRouteHandler.RegisterController<WithResponseContentControllerSample>();
var configuration = new HttpServerConfiguration()
.ListenOnPort(8800)
.RegisterRoute("api", restRouteHandler)
.RegisterRoute(new StaticFileRouteHandler(@"Restup.DemoStaticFiles\Web"))
.EnableCors(); // allow cors requests on all origins
// .EnableCors(x => x.AddAllowedOrigin("http://specificserver:<listen-port>"));
var httpServer = new HttpServer(configuration);
_httpServer = httpServer;
await httpServer.StartServerAsync();
// Dont release deferral, otherwise app will stop
}
示例13: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
// simple example with a Toast, to enable this go to manifest file
// and mark App as TastCapable - it won't work without this
// The Task will start but there will be no Toast.
//ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
//XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
//XmlNodeList textElements = toastXml.GetElementsByTagName("text");
//textElements[0].AppendChild(toastXml.CreateTextNode("My first Task - Yeah"));
//textElements[1].AppendChild(toastXml.CreateTextNode("I'm a message from your background task!"));
//ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
var deferral = taskInstance.GetDeferral();
RawNotification raw = taskInstance.TriggerDetails as RawNotification;
if (raw != null)
{
Debug.WriteLine(
string.Format("XXXXXXXXXXXXXReceived from cloud:XXXXXXXXXX [{0}]",
raw.Content));
}
deferral.Complete();
}
示例14: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
//
// TODO: Insert code to perform background work
//
// If you start any asynchronous methods here, prevent the task
// from closing prematurely by using BackgroundTaskDeferral as
// described in http://aka.ms/backgroundtaskdeferral
//
var deferral = taskInstance.GetDeferral();
var settings = new I2cConnectionSettings(I2C_ADDRESS);
settings.BusSpeed = I2cBusSpeed.FastMode;
var aqs = I2cDevice.GetDeviceSelector(); /* Get a selector string that will return all I2C controllers on the system */
var dis = await DeviceInformation.FindAllAsync(aqs); /* Find the I2C bus controller devices with our selector string */
_dht11 = await I2cDevice.FromIdAsync(dis[0].Id, settings); /* Create an I2cDevice with our selected bus controller and I2C settings */
await begin();
while (true)
{
var temp = await readTemperature();
var hum = await readHumidity();
Debug.WriteLine($"{temp} C & {hum}% humidity");
await Task.Delay(2000);
}
deferral.Complete();
}
示例15: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
Adapter adapter = null;
deferral = taskInstance.GetDeferral();
try
{
adapter = new Adapter();
dsbBridge = new DsbBridge(adapter);
var initResult = dsbBridge.Initialize();
if (initResult != 0)
{
throw new Exception("DSB Bridge initialization failed!");
}
}
catch (Exception ex)
{
if (dsbBridge != null)
{
dsbBridge.Shutdown();
}
if (adapter != null)
{
adapter.Shutdown();
}
throw;
}
}