locked
BackgroundTask with VB.NET RRS feed

  • Question

  • Hello.

    I am trying to create a background task with VB. This is what my code looks like :

    Imports Windows.ApplicationModel.Background

    Imports Windows.Storage

    Imports Windows.UI.Core

    Imports Windows.UI.Core.CoreWindow

    Imports System.Runtime.InteropServices

    Public NotInheritable Class clsBack

    Implements IBackgroundTask

    <DllImport("user32", setlasterror:=True)> _

    Public Shared Function SystemParametersInfo( _

    ByVal intAction As Integer, _

    ByVal intParam As Integer, _

    ByVal strParam As String, _

    ByVal intWinIniFlag As Integer) As Integer

    ' returns non-zero value if function succeeds

    End Function

    Const SPIF_UPDATEINIFILE = &H1

    Const SPI_SETDESKWALLPAPER = 20

    Const SPIF_SENDWININICHANGE = &H2

    Private arrFileNames() As String

    Public Cancelled As Boolean

    Public Sub Run(TaskInstance As IBackgroundTaskInstance)

    Dim Deferral As BackgroundTaskDeferral = taskInstance.GetDeferral()

    'Await blahbla

    Deferral.Complete()

    End Sub

    Public Shared Function RegisterBackgroundTask(TaskEntryPoint As String, TaskName As String, Trigger As IBackgroundTrigger, Condition As IBackgroundCondition) As BackgroundTaskRegistration

    For Each cur In BackgroundTaskRegistration.AllTasks

    If cur.Value.Name = TaskName Then

    Return DirectCast(cur.Value, BackgroundTaskRegistration)

    End If

    Next

    Dim Builder As New BackgroundTaskBuilder

    Builder.Name = TaskName

    Builder.TaskEntryPoint = TaskEntryPoint

    Builder.SetTrigger(Trigger)

    If Condition IsNot Nothing Then

    Builder.AddCondition(Condition)

    End If

    Dim task As BackgroundTaskRegistration = Builder.Register()

    Return task

    End Function

    Private Sub OnCompleted(Task As IBackgroundTaskRegistration, args As BackgroundTaskCompletedEventArgs)

    Dim Settings = ApplicationData.Current.LocalSettings

    Dim Key = Task.TaskId.ToString()

    Dim Message = Settings.Values(Key).ToString()

    ' UpdateUI()

    End Sub

    Private Async Function UpdateUI() As Task

    Dim MyDispatcher = GetForCurrentThread().Dispatcher

    Await MyDispatcher.RunAsync(CoreDispatcherPriority.Normal, Function()

    ' Dim strPicFileName As String = arrFileNames(lstFiles.SelectedIndex)

    ''Try 'Dim x As Integer

    'x = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0&, strPicFileName, SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE)

    ''Catch ex As Exception

    'Dim errorval As Integer

    'errorval = Marshal.GetLastWin32Error()

    'Debug.WriteLine(errorval)

    'Debug.WriteLine(x)

    'End Try

    End Function)

    End Function

    Public Shared Sub UnregisterBackgroundTasks(TaskName As String)

    For Each cur In BackgroundTaskRegistration.AllTasks

    If cur.Value.Name = TaskName Then

    cur.Value.Unregister(True)

    End If

    Next

    End Sub

    Public Sub OnCanceled(sender As IBackgroundTaskInstance, Reason As BackgroundTaskCancellationReason)

    Cancelled = True

    End Sub

    End Class

    It keeps on telling my that my class need to have Sub Run(TaskInstance As IBackgroundTaskInstance)  as I have.

    Any suggestions? Am I on the wrong path?

    Thursday, August 15, 2013 8:03 AM

Answers

  • Here is vb code for adding background task and task triggers as well as background task.

    In mainpage class :

    Public Async Function CheckIfBackgroundTaskExists() As Task
    
            Dim status As BackgroundAccessStatus = Await BackgroundExecutionManager.RequestAccessAsync()
    
            Dim taskStart As Boolean = BackgroundTaskRegistration.AllTasks.Any(Function(x) x.Value.Name = "MosaicBackgroundTask")
            If Not taskStart Then
                RegisterStartTask()
            End If
    
            Dim taskTimer As Boolean = BackgroundTaskRegistration.AllTasks.Any(Function(x) x.Value.Name = "MosaicBackgroundTaskTimer")
            If Not taskStart Then
                RegisterTimerTask()
            End If
    
        End Function
    
        Public Shared Sub RegisterStartTask()
    
            Dim builder As New BackgroundTaskBuilder()
            builder.Name = "MosaicBackgroundTask"
            builder.TaskEntryPoint = "MosaicTileClockUpdater.MosaicTileClockBackgroundTask"
            builder.SetTrigger(New SystemTrigger(SystemTriggerType.UserPresent, False))
            Dim task As BackgroundTaskRegistration = builder.Register()
    
        End Sub
    
        Public Shared Sub RegisterTimerTask()
    
            Dim builder2 As New BackgroundTaskBuilder()
            builder2.Name = "MosaicBackgroundTaskTimer"
            builder2.TaskEntryPoint = "MosaicTileClockUpdater.MosaicTileClockBackgroundTask"
            builder2.SetTrigger(New TimeTrigger(60, False))
            Dim task2 As BackgroundTaskRegistration = builder2.Register()
    
        End Sub

    Background task class :

    Imports Windows.ApplicationModel.Background
    Imports Windows.Data.Xml.Dom
    Imports Windows.UI.Notifications
    Imports Windows.UI.StartScreen
    
    Public NotInheritable Class MosaicTileClockBackgroundTask
        Implements IBackgroundTask
    
        Dim datetimenow As DateTime
    
        Public Sub Run(taskInstance As IBackgroundTaskInstance) Implements IBackgroundTask.Run
    
            datetimenow = DateTime.Now
            
            InitialUpdate()
            CreateSchedule()
    
        End Sub

    In the background tasks run sub are 2 methods which run and and make subsequent method and function calls.

    This vb code works so try adapting it to your needs and check that you have followed all the steps in the example correctly. Here is another link to check http://blogs.msdn.com/b/windowsappdev/archive/2012/05/24/being-productive-in-the-background-background-tasks.aspx

    Thursday, August 15, 2013 2:36 PM

All replies

  • Your background task registration and task builder code need to be in your main app class with the background task as a seperate class.

    Have a look here http://msdn.microsoft.com/en-us/library/windows/apps/hh977055.aspx

    Thursday, August 15, 2013 10:36 AM
  • Hi. Thanks for your interest!

    OK, so I should move the RegisterBackgroundTask to my main class. I'll give that a shot.

    The link you have provided is what I am trying to implement, I guess my English is bad or I read wrong.

    I'll keep you up to date!

    Thursday, August 15, 2013 10:55 AM
  • OK, I moved everything except for the Run sub out of my BackgroundTask, and still I get the same error

    Any help?

    Thursday, August 15, 2013 1:33 PM
  • In your example the run sub is commented out.

    Here is an example of  background task in vb

    Public NotInheritable Class BackgroundTask
        Implements IBackgroundTask
        
        Public Sub Run(taskInstance As IBackgroundTaskInstance) Implements IBackgroundTask.Run
    
            'Do some stuff here
            
        End Sub
        
    End Class
    That is the basics of it.

    Thursday, August 15, 2013 1:49 PM
  • Thanks again.

    It seems as if the code error messed up the code colours. It is indeed not commented, but here it displays green.

    I think, as there is no VB sample code given, that I'd have to do my Background task in C#, and the rest of my app in VB. This really sucks.

    Why does VB always have to play second fiddle to C#, especially when examples on Windows 8 are concerned?!

    If I hadn't known C#, this would have been really problematic and I hope that VB guys can eventually figure this out. It seems simple enough, but nothing! I have been working with VB for years, and I have always converted C# code to VB without issues, except for now, because there is lack of documentation.

    I'll let you know if my C# workaround ( which is unecessary in any logic sense ) works.

    Thursday, August 15, 2013 2:00 PM
  • Can you repost your code as it is now. Also have you registered the background task in the app manifest.

    Everything your background task needs to do must happen or be called from within the run sub. It also seems that you're trying to interact with windows functions which aren't available to windows apps.   

    Your background class also needs to be added to your solution as a new project

    Windows.ApplicationModel.Background namespace.

    1. Create a new project for background tasks and add it to your solution. To do this, right-click on your solution and select Add->New Project. Then select the Windows Runtime Component project type, name the project, and click OK.
    2. Reference the background tasks project from your Windows Store app project. First, right-click on your Windows Store app project and select Properties. Then go to Common Properties and click Add New Reference, check the box next to your background tasks project, and click OK on both dialogs.
    3. Create a new class that implements the IBackgroundTask interface. The Runmethod is a required entry point that will be called when the specified event is triggered; this method is required in every background task.

    • Edited by Peter DC Thursday, August 15, 2013 2:29 PM
    Thursday, August 15, 2013 2:14 PM
  • Here is vb code for adding background task and task triggers as well as background task.

    In mainpage class :

    Public Async Function CheckIfBackgroundTaskExists() As Task
    
            Dim status As BackgroundAccessStatus = Await BackgroundExecutionManager.RequestAccessAsync()
    
            Dim taskStart As Boolean = BackgroundTaskRegistration.AllTasks.Any(Function(x) x.Value.Name = "MosaicBackgroundTask")
            If Not taskStart Then
                RegisterStartTask()
            End If
    
            Dim taskTimer As Boolean = BackgroundTaskRegistration.AllTasks.Any(Function(x) x.Value.Name = "MosaicBackgroundTaskTimer")
            If Not taskStart Then
                RegisterTimerTask()
            End If
    
        End Function
    
        Public Shared Sub RegisterStartTask()
    
            Dim builder As New BackgroundTaskBuilder()
            builder.Name = "MosaicBackgroundTask"
            builder.TaskEntryPoint = "MosaicTileClockUpdater.MosaicTileClockBackgroundTask"
            builder.SetTrigger(New SystemTrigger(SystemTriggerType.UserPresent, False))
            Dim task As BackgroundTaskRegistration = builder.Register()
    
        End Sub
    
        Public Shared Sub RegisterTimerTask()
    
            Dim builder2 As New BackgroundTaskBuilder()
            builder2.Name = "MosaicBackgroundTaskTimer"
            builder2.TaskEntryPoint = "MosaicTileClockUpdater.MosaicTileClockBackgroundTask"
            builder2.SetTrigger(New TimeTrigger(60, False))
            Dim task2 As BackgroundTaskRegistration = builder2.Register()
    
        End Sub

    Background task class :

    Imports Windows.ApplicationModel.Background
    Imports Windows.Data.Xml.Dom
    Imports Windows.UI.Notifications
    Imports Windows.UI.StartScreen
    
    Public NotInheritable Class MosaicTileClockBackgroundTask
        Implements IBackgroundTask
    
        Dim datetimenow As DateTime
    
        Public Sub Run(taskInstance As IBackgroundTaskInstance) Implements IBackgroundTask.Run
    
            datetimenow = DateTime.Now
            
            InitialUpdate()
            CreateSchedule()
    
        End Sub

    In the background tasks run sub are 2 methods which run and and make subsequent method and function calls.

    This vb code works so try adapting it to your needs and check that you have followed all the steps in the example correctly. Here is another link to check http://blogs.msdn.com/b/windowsappdev/archive/2012/05/24/being-productive-in-the-background-background-tasks.aspx

    Thursday, August 15, 2013 2:36 PM
  • Wow, thanks for your continuous effort to help an old burnt out programmer like me.

    I'll try to implement your code, then take it from there. I will let you know how it goes!

    Thanks once again, and have a blessed night

    Hannes

    Friday, August 16, 2013 6:11 AM
  • There is no limit to my stupidity and how thankful I ma for you pointing it out :)

    Thanks for all your help

    Monday, August 19, 2013 11:06 AM
  • You're welcome , please bear in mind that I'm only able to help because I've had the same issues.
    Monday, August 19, 2013 11:12 AM