I am not quite sure if this has been asked before but I have searched google but nothing much came up with this problem. I have 2 apps which are submitted to store and they both have almost same background tasks, specifically 2 tasks each.
I register the background tasks, when the app starts and if the app gets updated I check the app version and do things appropriately as described in Microsoft Documentation for UWP apps for Out-of-Process Background Tasks.
The background tasks were working fine before but for a number of days till now, I didn't see any activity regarding background tasks in my system. I checked the event viewer and I saw that according to the triggers defined in the apps the background tasks do "try to start" but there is some problem with the system when the Tasks get killed with exceptions and never actually run.
Please note that while Debugging I can surely run the background Tasks without any problems, the tasks don't run when they start on their own.
Following are the screenshots for event viewer latest logs:
Task 1 for WFW Movies & TV
Task 2 for WFW Movies & TV
Task 1 for Anime Deed
Task 2 for Anime Deed
The code I use for registration for tasks:
private static async void BackgroundTasksRegistrationProcedure()
{
string curVer = DataHelper.GetAppVersion();
TimeTrigger timeTrigger = new TimeTrigger(15, false);
SystemCondition internetCondition = new SystemCondition(SystemConditionType.InternetAvailable);
bool doRegister = false;
var status1 = await BackgroundExecutionManager.RequestAccessAsync();
switch (status1)
{
case BackgroundAccessStatus.DeniedByUser:
{
doRegister = false;
break;
}
case BackgroundAccessStatus.AllowedSubjectToSystemPolicy:
{
doRegister = true;
break;
}
case BackgroundAccessStatus.AlwaysAllowed:
{
doRegister = true;
break;
}
default:
break;
}
var versionKey = "app_version";
if (!DataHelper.LocalDataContainer.Values.ContainsKey(versionKey))
{
DataHelper.LocalDataContainer.Values[versionKey] = curVer;
// run tasks registration here
if (doRegister)
{
RegisterBackgroundTask(EpisodeUpdateTaskEntryPoint, EpisodeUpdateTaskName, new TimeTrigger(120, false), internetCondition);
RegisterBackgroundTask(TileUpdateTaskEntryPoint, TileUpdateTaskName, timeTrigger, internetCondition);
}
}
else
{
// compare app version
if (DataHelper.LocalDataContainer.Values[versionKey].ToString() == curVer)
{
// run tasks registration here
if (doRegister)
{
RegisterBackgroundTask(EpisodeUpdateTaskEntryPoint, EpisodeUpdateTaskName, new TimeTrigger(120, false), internetCondition);
RegisterBackgroundTask(TileUpdateTaskEntryPoint, TileUpdateTaskName, timeTrigger, internetCondition);
}
}
else
{
DataHelper.LocalDataContainer.Values[versionKey] = curVer;
// remove task registrations
BackgroundExecutionManager.RemoveAccess();
// run tasks registrations
await BackgroundExecutionManager.RequestAccessAsync();
if (doRegister)
{
RegisterBackgroundTask(EpisodeUpdateTaskEntryPoint, EpisodeUpdateTaskName, new TimeTrigger(120, false), internetCondition);
RegisterBackgroundTask(TileUpdateTaskEntryPoint, TileUpdateTaskName, timeTrigger, internetCondition);
}
}
}
}
public static BackgroundTaskRegistration RegisterBackgroundTask(string taskEntryPoint, string name, IBackgroundTrigger trigger, IBackgroundCondition condition)
{
// We'll add code to this function in subsequent steps.
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == name)
{
//
// The task is already registered.
//
return (BackgroundTaskRegistration)(cur.Value);
}
}
var builder = new BackgroundTaskBuilder()
{
Name = name
};
// in-process background tasks don't set TaskEntryPoint
if (taskEntryPoint != null && taskEntryPoint != string.Empty)
{
builder.TaskEntryPoint = taskEntryPoint;
}
builder.SetTrigger(trigger);
if (condition != null)
{
builder.AddCondition(condition);
}
BackgroundTaskRegistration task = builder.Register();
return task;
}
Please help me understand why this is happening. I can Debug the tasks successfully but they don't run on their own when the app is not running. Thanks
Update:
I have found another error relating to BackgroundTaskHost.exe
Faulting application name: backgroundTaskHost.exe, version: 10.0.15063.0, time stamp: 0x9ad06afb
Faulting module name: CoreCLR.dll, version: 4.6.25129.1, time stamp: 0x58dc3e7d
Exception code: 0xc0000005
Fault offset: 0x0014101d
Faulting process ID: 0x18bc
Faulting application start time: 0x01d2d953c94d6e41
Faulting application path: C:\Windows\syswow64\backgroundTaskHost.exe
Faulting module path: C:\Program Files\WindowsApps\Microsoft.NET.CoreRuntime.1.1_1.1.25129.1_x86__8wekyb3d8bbwe\CoreCLR.dll
Report ID: 8a3a3035-d95b-49bb-a106-d645c604c39b
Faulting package full name: 51918AhmarAftab.WFWMoviesTV_1.3.442.0_x86__rm40d0p5knk1c
Faulting package-relative application ID: App
I think it's a windows issue considering the fault is in .Net.CoreRuntime.
Related
The application exits with:
The program '[12868] AppName.vshost.exe' has exited with code 1073741855 (0x4000001f).
Below Code:
Call Export() twice after each other: crash with above logging
Call the contents of Export() inside Export() twice (the inner scope), and it doesn't crash.
This is reproducible, I have no idea where to start.
private void btnExport_Click(object sender, RoutedEventArgs e)
{
Enable(false);
statusbar.Message = "Exporting...";
Task t = new Task(Export);
t.ContinueWith(ExportEnd);
t.Start();
}
private void Export()
{
{
PBNSectionDictionary source = ctrlSectionSelection.SectionSelection.SelectSections;
PBNSectionDictionary dict = new PBNSectionDictionary();
foreach (string sectionType in source.Keys)
{
if (source[sectionType] != null)
{
dict[sectionType] = collector.ReadFullSection(source[sectionType]);
}
}
PBNFMV.Export.PBNExport export = new PBNFMV.Export.PBNExport(new Lms.Custom.Files.AdvancedFileLocator(Constants.NAME), dict, manager);
export.Export();
dict.Dispose();
}
}
private void ExportEnd(Task t)
{
Enable(true);
statusbar.Message = "Export done";
}
Event log:
Faulting application name: PBNFMV.exe, version: 16.2.0.0, time stamp: 0x58aeadf2
Faulting module name: ntdll.dll, version: 6.1.7601.23569, time stamp: 0x57f7bb79
Exception code: 0xc0000374
Fault offset: 0x000ce8fb
Faulting process id: 0xbd4
Faulting application start time: 0x01d28db92a6d6c1e
Faulting application path: C:\APPPATH\source\PBNFMV\bin\Debug\PBNFMV.exe
Faulting module path: C:\windows\SysWOW64\ntdll.dll
Report Id: 72f988f9-f9ac-11e6-8d91-000acd1f71fd
Exception settings completely enabled:
C++ exceptions
common language runtime exceptions
gpu memory access exceptions
managed debugging assitants
win32 exceptions
The issue is solved.
Hence: very strange.
It was due to construction of an object further (!) in code execution, which made things crash (because of a bad implementation in a library).
The strange part is why that object was already instantiated, i believe some optimalisation in the .net runtime.
Apologies
Scratching my head on this one.
I've got a background task in my UWP application which is registered to run every 15 minutes (using TimeTrigger) and whenever the internet becomes available (using a SystemTrigger). I know for a fact that these are registered correctly as both appear in the "Lifecycle Events" when debugging using visual studio. Nevertheless, my code for registering them is below:
bool registered1 = false;
bool registered2 = false;
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == "BackgroundGPS")
{
registered1 = true;
}
if (task.Value.Name == "InternetAvailGPS")
{
registered2 = true;
}
}
await BackgroundExecutionManager.RequestAccessAsync();
if (!registered1)
{
var builder1 = new BackgroundTaskBuilder();
builder1.Name = "BackgroundGPS";
builder1.TaskEntryPoint = "BackgroundTasks.BackgroundGPSTask";
var triggerTime = new TimeTrigger(15, false);
builder1.SetTrigger(triggerTime);
BackgroundTaskRegistration task1 = builder1.Register();
}
if (!registered2)
{
var builder2 = new BackgroundTaskBuilder();
builder2.Name = "InternetAvailGPS";
builder2.TaskEntryPoint = "BackgroundTasks.BackgroundGPSTask";
var triggerIA = new SystemTrigger(SystemTriggerType.InternetAvailable, false);
builder2.SetTrigger(triggerIA);
BackgroundTaskRegistration task2 = builder2.Register();
}
I have ensured that the tasks are declared correctly in my manifest. If they weren't, my app would be throwing an exception when trying to register them.
If I run in debug mode I can see that both BackgroundGPS and InternetAvailGPS are shown in the Lifecycle Events. However, when I click on either of them to force them to execute, I get the following in the output window:
The program '[4728] backgroundTaskHost.exe' has exited with code 1 (0x1).
I have a breakpoint set at the first line of code in my 'Run' method of the background task but this is never hit. The background task is never loaded nor run, and I've no idea why. This probably isn't an issue with my Run method, but it looks like this (I've omitted much of the meat of it, and just included the beginning and end)
public async void Run(IBackgroundTaskInstance taskInstance)
{
Debug.WriteLine("GPS Started");
int errCode = 0;
try
{
_deferral = taskInstance.GetDeferral();
saveGPSStatus(DateTime.Now.ToString(), "", " ");
var access = await Geolocator.RequestAccessAsync();
if (access != GeolocationAccessStatus.Allowed)
{
Debug.WriteLine("No access");
saveGPSStatus("", "", "No GPS Access");
return;
}
Geolocator locator = new Geolocator();
locator.DesiredAccuracyInMeters = 100;
Geoposition position = await locator.GetGeopositionAsync();
//Stuff goes on in here
_deferral.Complete();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
saveGPSStatus("", "", "Unexpected error. Err code "+errCode+". " + e.Message);
_deferral.Complete();
}
}
I have tried this both on a Windows Phone and a Windows Tablet both running build 10.0.10586.164, and they both do not execute my background task.
As I said above, these were working perfectly a few weeks ago and have only realised something was wrong as some of the app's users have been complaining!
Any help is greatly appreciated.
Got it working in the end, I was simply missing a reference to my background task project within my main project. I must have deleted it by accident at some point before that.
Just to expand on not having it referenced, not having the correct TaskEntryPoint namespace and class name will also cause this error. For me, I misspelt the class name.
When running locally in the emulator the web worker works fine. However whenever I update my web worker running on an Azure VM I get the following exceptions exceptions in the event viewer and the role won't start:
Application: WaWorkerHost.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AggregateException
Stack:
at System.Threading.Tasks.Task.Wait(Int32, System.Threading.CancellationToken)
at System.Threading.Tasks.Task.Wait()
at Foo.PushProcess.WorkerRole.Run()
at Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.StartRoleInternal()
at Microsoft.WindowsAzure.ServiceRuntime.Implementation.Loader.RoleRuntimeBridge.b__2()
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()
Inner Exception: A task was canceled.
Faulting application name: WaWorkerHost.exe, version: 2.6.1198.712, time stamp: 0x54eba731
Faulting module name: KERNELBASE.dll, version: 6.3.9600.17415, time stamp: 0x54505737
Exception code: 0xe0434352
Fault offset: 0x0000000000008b9c
Faulting process id: 0xfb8
Faulting application start time: 0x01d11e3128981a5d
Faulting application path: E:\base\x64\WaWorkerHost.exe
Faulting module path: D:\Windows\system32\KERNELBASE.dll
Report Id: 30631c5c-8a25-11e5-80c6-000d3a22f3ec
Faulting package full name:
Faulting package-relative application ID:
Session "MA_ETWSESSION_WAD_415df88f8a0447178dbd4c18f1349f0e_Foo.PushProcess_Foo.PushProcess_IN_0" failed to start with the following error: 0xC0000035
This is the relevant code:
public override void Run()
{
Trace.TraceInformation("Foo.PushProcess is running");
try
{
RunAsync(_cancellationTokenSource.Token).Wait(); // This is where the exceptions point to
}
catch (Exception ex)
{
Trace.TraceError("[WORKER] Run error: " + ex);
}
finally
{
_runCompleteEvent.Set();
}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
bool result = base.OnStart();
_storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
var queueClient = _storageAccount.CreateCloudQueueClient();
_pushQueue = queueClient.GetQueueReference("pushes");
_pushQueue.CreateIfNotExists();
CreatePushBroker();
Trace.TraceInformation("Foo.PushProcess has been started");
return result;
}
private async Task RunAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
Trace.TraceInformation("Working");
CloudQueueMessage message = null;
try
{
message = _pushQueue.GetMessage();
if (message != null)
{
ProcessItem(message);
}
}
catch (Exception ex)
{
if (message != null && message.DequeueCount > 5)
_pushQueue.DeleteMessage(message);
Trace.TraceError("[WORKER] Retrieval Failure: " + ex);
}
await Task.Delay(1000, cancellationToken);
}
}
Note some code has been omitted, however that is all run after the initialisation and in theory isn't reached by this exception.
I am completely at a loss as to what could cause this issue. Any help would be appreciated - even if only to aid me getting a helpful exception.
UPDATE
I have now reduced my code to the below - it is as simple as a web worker can possibly be - and I am still getting the exceptions. I believe that either the old worker is being cached, or there is an issue in the deployment procedure.
public override void Run()
{
Trace.TraceInformation("Foo.PushProcess is running");
try
{
RunAsync(_cancellationTokenSource.Token).Wait(); // This is where the exceptions point to
}
catch (Exception ex)
{
Trace.TraceError("[WORKER] Run error: " + ex);
}
finally
{
_runCompleteEvent.Set();
}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
bool result = base.OnStart();
return result;
}
private async Task RunAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
Trace.TraceInformation("Working");
// code removed for testing - no work is being done.
await Task.Delay(1000, cancellationToken);
}
}
I gave this a whirl and wasn't able to get this to repro on my end. I have VS 2015 Enterprise (14.0.23107.0 D14REL) from a MSDN Azure image I deployed running with .Net Fx version 4.6. I have Azure Tools and SDK 2.8 installed. I created a new Azure Cloud Service using .NET Fx 4.5.2 and I add a single worker role.
I just ran some sparse code template from yours as follows:
public class WorkerRole : RoleEntryPoint
{
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);
private CloudQueue _pushQueue;
private CloudStorageAccount _storageAccount;
public override void Run()
{
Trace.TraceInformation("WorkerRole1 is running");
try
{
this.RunAsync(this.cancellationTokenSource.Token).Wait();
}
catch (Exception ex)
{
Trace.TraceError("[WORKER] Run error: " + ex);
}
finally
{
this.runCompleteEvent.Set();
}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
bool result = base.OnStart();
_storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
var queueClient = _storageAccount.CreateCloudQueueClient();
_pushQueue = queueClient.GetQueueReference("pushes");
_pushQueue.CreateIfNotExists();
CreatePushBroker();
Trace.TraceInformation("Foo.PushProcess has been started");
return result;
}
private void CreatePushBroker()
{
return;
}
public override void OnStop()
{
Trace.TraceInformation("WorkerRole1 is stopping");
this.cancellationTokenSource.Cancel();
this.runCompleteEvent.WaitOne();
base.OnStop();
Trace.TraceInformation("WorkerRole1 has stopped");
}
private async Task RunAsync(CancellationToken cancellationToken)
{
// TODO: Replace the following with your own logic.
while (!cancellationToken.IsCancellationRequested)
{
Trace.TraceInformation("Working");
CloudQueueMessage message = null;
try
{
message = _pushQueue.GetMessage();
if (message != null)
{
ProcessItem(message);
}
}
catch (Exception ex)
{
if (message != null && message.DequeueCount > 5)
_pushQueue.DeleteMessage(message);
Trace.TraceError("[WORKER] Retrieval Failure: " + ex);
}
await Task.Delay(1000, cancellationToken);
}
}
private void ProcessItem(CloudQueueMessage message)
{
return;
}
}
}
That runs without issue in the local emulator, and I went ahead and deployed it to West US with IntelliTrace enabled, on a small instance VM, and had n deployment issues. It is running on a WA-GUEST-OS-4.26_201511-0 guest worker role image, and I was able to RDP into the machine, and I didn't see any issues related to the code or the machine. DO you have any other binaries you might not be including in your packages, or perhaps there are some dependencies not defined properly, or storage account naming issues?
Here was the deployment log for me. As you can see, it took about 7 minutes as I had it pull storage from East US just for fun:
1:11:25 AM - Warning: There are package validation warnings.
1:11:26 AM - Checking for Remote Desktop certificate...
1:11:26 AM - Uploading Certificates...
1:11:42 AM - Applying Diagnostics extension.
1:12:24 AM - Preparing deployment for AzureCloudService1 - 11/24/2015 1:11:19 AM with Subscription ID '9a4715f5-acb8-4a18-8259-1c28b92XXXXX' using Service Management URL 'https://management.core.windows.net/'...
1:12:24 AM - Connecting...
1:12:24 AM - Verifying storage account 'ericgoleastus'...
1:12:24 AM - Uploading Package...
1:12:28 AM - Creating...
1:13:15 AM - Created Deployment ID: c5f26568707b46a3bd42466dd0bf7509.
1:13:15 AM - Instance 0 of role WorkerRole1 is creating the virtual machine
1:13:15 AM - Starting...
1:13:32 AM - Initializing...
1:14:36 AM - Instance 0 of role WorkerRole1 is starting the virtual machine
1:16:11 AM - Instance 0 of role WorkerRole1 is in an unknown state
1:16:43 AM - Instance 0 of role WorkerRole1 is busy
Details: Starting role... System is initializing. [2015-11-24T01:16:08Z]
1:19:50 AM - Instance 0 of role WorkerRole1 is ready
1:19:50 AM - Created web app URL: http://quequetest.cloudapp.net/
1:19:50 AM - Complete.
Let us know if you can get some more details possibly with IntelliTrace enabled.
Regards,
Eric
To fix this issue I simply deleted the original Cloud VM instance which held the worker role, recreated it and re-published the role. From that point it has worked absolutely fine.
I am still unable to determine what caused the error, and have had no further issues like this with any other worker role. My assumption here was that there was a configuration issue with the VM which could not be amended through code or the Azure portal.
I'm using a Microsoft azure service bus queue to process calculations and my program runs fine for a few hours but then I start to get this exception for every message that I process from then on. I have no clue where to start since everything runs fine for the first few hours. My code seems to be accurate as well. I will post the method where I handle the azure service bus message.
public static async Task processCalculations(BrokeredMessage message)
{
try
{
if (message != null)
{
if (connection == null || !connection.IsConnected)
{
connection = await ConnectionMultiplexer.ConnectAsync("connection,SyncTimeout=10000,ConnectTimeout=10000");
//connection = ConnectionMultiplexer.Connect("connection,SyncTimeout=10000,ConnectTimeout=10000");
}
cache = connection.GetDatabase();
string sandpKey = message.Properties["sandp"].ToString();
string dateKey = message.Properties["date"].ToString();
string symbolclassKey = message.Properties["symbolclass"].ToString();
string stockdataKey = message.Properties["stockdata"].ToString();
string stockcomparedataKey = message.Properties["stockcomparedata"].ToString();
var sandpTask = cache.GetAsync<List<StockData>>(sandpKey);
var dateTask = cache.GetAsync<DateTime>(dateKey);
var symbolinfoTask = cache.GetAsync<SymbolInfo>(symbolclassKey);
var stockdataTask = cache.GetAsync<List<StockData>>(stockdataKey);
var stockcomparedataTask = cache.GetAsync<List<StockMarketCompare>>(stockcomparedataKey);
await Task.WhenAll(sandpTask, dateTask, symbolinfoTask,
stockdataTask, stockcomparedataTask);
List<StockData> sandp = sandpTask.Result;
DateTime date = dateTask.Result;
SymbolInfo symbolinfo = symbolinfoTask.Result;
List<StockData> stockdata = stockdataTask.Result;
List<StockMarketCompare> stockcomparedata = stockcomparedataTask.Result;
StockRating rating = performCalculations(symbolinfo, date, sandp, stockdata, stockcomparedata);
if (rating != null)
{
saveToTable(rating);
if (message.LockedUntilUtc.Minute <= 1)
{
await message.RenewLockAsync();
}
await message.CompleteAsync(); // getting exception here
}
else
{
Console.WriteLine("Message " + message.MessageId + " Completed!");
await message.CompleteAsync();
}
}
}
catch (TimeoutException time)
{
Console.WriteLine(time.Message);
}
catch (MessageLockLostException locks)
{
Console.WriteLine(locks.Message);
}
catch (RedisConnectionException redis)
{
Console.WriteLine("Start the redis server service!");
}
catch (MessagingCommunicationException communication)
{
Console.WriteLine(communication.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
UPDATE: I check the time until the lock expiration and I call lock renew if it needs it but it renews the lock with no errors but I'm still getting this exception.
timeLeft = message.LockedUntilUtc - DateTime.UtcNow;
if (timeLeft.TotalMinutes <= 2)
{
//Console.WriteLine("Renewed lock! " + ((TimeSpan)(message.LockedUntilUtc - DateTime.UtcNow)).TotalMinutes);
message.RenewLock();
}
catch (MessageLockLostException locks)
{
Console.WriteLine("Delivery Count: " + message.DeliveryCount);
Console.WriteLine("Enqueued Time: " + message.EnqueuedTimeUtc);
Console.WriteLine("Expires Time: " + message.ExpiresAtUtc);
Console.WriteLine("Locked Until Time: " + message.LockedUntilUtc);
Console.WriteLine("Scheduled Enqueue Time: " + message.ScheduledEnqueueTimeUtc);
Console.WriteLine("Current Time: " + DateTime.UtcNow);
Console.WriteLine("Time Left: " + timeLeft);
}
All I know so far is that my code runs fine for awhile and the renew lock gets called and works but I'm still getting the lock exception and inside that exception, I output the timeleft and it keeps increasing the time difference as the code runs which makes me believe that the time until lock expiration is not being changed somehow?
I spent hours trying understand why I was getting a MessageLockLostException. The reason for me was due to AutoComplete defaulting to true.
If you're going to call messsage.Complete() (or CompleteAsync()) then you should instantiate an OnMessageOptions object, set AutoComplete to false, and pass it into your OnMessage call.
var options = new OnMessageOptions();
options.AutoComplete = false;
client.OnMessage(processCalculations, options);
It took me 2 days to resolve similar issue - same exception.
This exception may have multiple reasons, I'll describe couple of config options that may help you stranger...
ServiceBus Queue or Topic-subscription config:
Message lock duration on Queue / Topic subscription is too low set it to approx. message processing time
ServiceBusClient options config:
tryTimeout is too short, set it to ~10s for diagnostics
ServiceBusProcessor options config:
AutoCompleteMessages is by default set to true, set it to false
PrefetchCount is too high, for diagnostics set it to 0
ReceiveMode set it to ServiceBusReceiveMode.PeekLock
MaxConcurrentCalls for diagnostics set it to 1
After finding correct values (optimized for a given system) I no longer observed any issues.
I was having a similar issue. Messages were being handled successfully, but when they went to complete, the Service Bus didn't have a valid lock anymore. It turns out my TopicClient.PrefetchCount was too high.
It appears that the lock begins on all prefetched messages as soon as they are fetched. If your cumulative message processing time surpasses the lock timeout every other prefetched message will fail to complete. It will return to the service bus.
In my case, it was just that I was working on a V2 on my local machine while I had the V1 already deployed up-and-running.
As the V1 was deployed in Azure (closer to the same Queue) and compiled in release mode (versus my local version in debug mode), the deployed version was always "winning" the concurrency for the queue resource.
That's why the message was no longer in the queue: It was consumed by the deployed version of my code. I know it is a little bit dumb.
Instead of renewing the lock manualy, when you create the client subscription, try auto renewing it using the client's OnMessageOptions() like this:
OnMessageOptions options = new OnMessageOptions();
options.AutoRenewTimeout = TimeSpan.FromMinutes(1);
try
{
client = Subscription.CreateClient();
client.OnMessageAsync(MessageReceivedComplete, options);
}
catch (Exception ex)
{
throw new Exception (ex);
}
I have been trying to write Background Task that would show raw push notification as toast. I got push notifications working when app is running.
This is my background task class:
public sealed class BackgroundNotificationsTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
string content = notification.Content;
Debug.WriteLine("Background raw notification obtained!");
//SendNotification(content);
}
private void SendNotification(string text)
{
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
XmlNodeList elements = toastXml.GetElementsByTagName("text");
foreach (IXmlNode node in elements)
{
node.InnerText = text;
}
ToastNotification notification = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(notification);
}
}
Then I Register In MainPage.xaml.cs
private void RegisterTasks()
{
BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
var taskRegistered = false;
var exampleTaskName = "NotificationsBackground";
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == exampleTaskName)
{
taskRegistered = true;
break;
}
}
if(!taskRegistered)
{
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "BackgroundTasks.NotificationsBackground";
builder.SetTrigger(new Windows.ApplicationModel.Background.PushNotificationTrigger());
try
{
BackgroundTaskRegistration task = builder.Register();
Debug.WriteLine("Background Task registered.");
}
catch (Exception e)
{
Debug.WriteLine("Background Task register exception: " + e.ToString());
}
}
}
Now in appxmanifest I have set 'Lock screen notifications' to Badge, then in Declarations I have added Background Task with properies Push notification selected and entry point set as BackgroundNotificationsTask.cs
![screen][2]
Am I doing something wron or is there something that I am missing?
EDIT:
Right now when i obtain push notification the app closes... anyone know why?
There are a couple of things you're doing wrong.
1) Put your BackgroundTask in a separate project
BackgroundTask projects should be Windows Runtime Components. Also make sure that your background task resides under an accessible namespace. Do not forget to reference the background task project from your app project.
2) Register the correct class
When registering your background task, always use the fully qualified class name and not the file name:
BackgroundTasks.BackgroundNotificationsTask
This is the entry point you'll have to use in the package manifest file and in your code (given that the task class is in the project explained under 1) and the namespace is called BackgroundTasks).
3) Call RequestAccessAsync()
Make sure you call this before registering any tasks:
BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
Edit: There is a pretty good walkthrough on MSDN https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977055.aspx