本文整理汇总了C#中IBackgroundTaskInstance类的典型用法代码示例。如果您正苦于以下问题:C# IBackgroundTaskInstance类的具体用法?C# IBackgroundTaskInstance怎么用?C# IBackgroundTaskInstance使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
IBackgroundTaskInstance类属于命名空间,在下文中一共展示了IBackgroundTaskInstance类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
}
开发者ID:jonclow,项目名称:iot-build-lab,代码行数:31,代码来源:StartupTask.cs
示例2: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
var updater = new LiveTileScheduler();
await updater.CreateSchedule();
deferral.Complete();
}
开发者ID:BerserkerDotNet,项目名称:UniversalWorldClock,代码行数:7,代码来源:TileSchedulerTask.cs
示例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();
}
}
开发者ID:pglazkov,项目名称:Linqua,代码行数:32,代码来源:SynchronizationTask.cs
示例4: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
deferral = taskInstance.GetDeferral();
Initialize();
Start();
}
开发者ID:micklab,项目名称:isavewater,代码行数:7,代码来源:StartupTask.cs
示例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();
}
开发者ID:JulianMH,项目名称:music-3,代码行数:35,代码来源:AudioPlayer.cs
示例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);
}
开发者ID:RasmusTG,项目名称:Windows-universal-samples,代码行数:36,代码来源:CompletionGroupTask.cs
示例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());
}
}
}
开发者ID:CleoQc,项目名称:GrovePi,代码行数:28,代码来源:StartupTask.cs
示例8: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
deferral = taskInstance.GetDeferral();
InitGPIO();
timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500));
}
开发者ID:Rbecca,项目名称:samples,代码行数:7,代码来源:StartupTask.cs
示例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();
}
}
开发者ID:dfdcastro,项目名称:TDC2015,代码行数:34,代码来源:TileUpdaterTask.cs
示例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();
}
开发者ID:chrissimusokwe,项目名称:TrainingContent,代码行数:33,代码来源:TheTask.cs
示例11: OnCanceled
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
_cancelRequested = true;
_cancelReason = reason;
Debug.WriteLine($"Background '{sender.Task.Name}' Cancel Requested...");
}
开发者ID:mohamedmansour,项目名称:MyElectricCar,代码行数:7,代码来源:MyElectricCarMonitorTask.cs
示例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
}
开发者ID:Jark,项目名称:restup,代码行数:35,代码来源:StartupTask.cs
示例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();
}
开发者ID:kleitz,项目名称:WPApp,代码行数:26,代码来源:MyBackground.cs
示例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();
}
开发者ID:ZenRobotic,项目名称:DisplayBadge,代码行数:27,代码来源:StartupTask.cs
示例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;
}
}
开发者ID:futurice,项目名称:AllJoynPhilipsHueDSB,代码行数:31,代码来源:StartupTask.cs
示例16: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
var deferal = taskInstance.GetDeferral();
if (taskInstance.TriggerDetails is RawNotification)
{
var details = taskInstance.TriggerDetails as RawNotification;
var arguments = details.Content.Split(':');
if (arguments.Count() > 0)
{
switch (arguments[0])
{
case "new_items":
if (arguments.Count() > 1)
{
XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");
badgeElement.SetAttribute("value", arguments[1]);
BadgeNotification badge = new BadgeNotification(badgeXml);
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
}
break;
}
}
}
deferal.Complete();
}
开发者ID:Ronacs,项目名称:WinDevCamp,代码行数:35,代码来源:RawNotificationTask.cs
示例17: Run
//
// The Run method is the entry point of a background task.
//
public void Run(IBackgroundTaskInstance taskInstance)
{
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");
// For performing asynchronous operations in the background task
BackgroundTaskDeferral asyncDeferral = taskInstance.GetDeferral();
//
// Query BackgroundWorkCost
// Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
// of work in the background task and return immediately.
//
var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
var settings = ApplicationData.Current.LocalSettings;
settings.Values["BackgroundWorkCost"] = cost.ToString();
//
// Associate a cancellation handler with the background task.
//
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
//
// Get the deferral object from the task instance, and take a reference to the taskInstance;
//
_deferral = taskInstance.GetDeferral();
_taskInstance = taskInstance;
_periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
asyncDeferral.Complete();
}
开发者ID:vinayganesh,项目名称:Wp8.1BackgroundTask,代码行数:37,代码来源:TimerTrigger.cs
示例18: TaskInstance_Canceled
private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
if (this.deferral != null)
{
this.deferral.Complete();
}
}
开发者ID:muneneevans,项目名称:blog,代码行数:7,代码来源:Grocery.cs
示例19: Run
public void Run(IBackgroundTaskInstance taskInstance)
{
try
{
if (Hub.Instance.VoipTaskInstance != null)
{
Debug.WriteLine("VoipTask already started.");
return;
}
_deferral = taskInstance.GetDeferral();
Hub.Instance.VoipTaskInstance = this;
Debug.WriteLine($"{DateTime.Now} VoipTask started.");
taskInstance.Canceled += (s, e) => CloseVoipTask();
}
catch (Exception e)
{
if (Hub.Instance.IsAppInsightsEnabled)
{
Hub.Instance.RTCStatsManager.TrackException(e);
}
if (_deferral != null)
{
_deferral.Complete();
}
throw e;
}
}
开发者ID:hungdluit,项目名称:ChatterBox,代码行数:28,代码来源:VoipTask.cs
示例20: Run
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
taskInstance.Canceled += TaskInstance_Canceled;
var triggerDetails = taskInstance.TriggerDetails
as AppServiceTriggerDetails;
if (triggerDetails?.Name != nameof(VoiceCommandService))
return;
var connection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
connection.VoiceCommandCompleted += ConnectionOnVoiceCommandCompleted;
var command = await connection.GetVoiceCommandAsync();
//even if it's not used, you can run into issues without this line.
switch (command.CommandName)
{
case "ReadTodaysNamedays":
await HandleReadNamedaysCommandAsync(connection);
break;
}
deferral.Complete();
}
开发者ID:codinesh,项目名称:LearningUWP,代码行数:29,代码来源:VoiceCommandService.cs
注:本文中的IBackgroundTaskInstance类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论