locked
How to listen C# events from the JavaScript?

    Question

  • Could you please advise how to listen C# background task in the main JavaScript App.

    I'm implementing something like that logic:

    And I cannot add listener for some event in the C# background task and also push this event.

    Many thanks for any help! 


    • Edited by _dima Wednesday, March 05, 2014 2:26 PM
    Wednesday, March 05, 2014 2:25 PM

All replies

  • See How to monitor background task progress and completion

    What sort of notifications are you trying to send? Background tasks and the main app cannot be tightly coupled. You cannot raise C# events from a background task and handle it in the main app.

    The only reliable way to share state between the background task and the foreground app is to use persistent storage such as the application data folders. You can have the main app monitor one of its local folders for changes and have the background task save data to it.

    See the Introduction to Background Tasks whitepaper for more details.

    --Rob

    Thursday, March 06, 2014 1:35 AM
    Moderator
  • Hi Rob,

    Many thanks for useful article. Maybe I had to find it myself and read it before posting of the question.

    So...

    We can add listener in the JavaScript for BackgroundTaskRegistration object, something like this:

    //methods in the main JavaScript app for receiving of the background task notifications
    function onCompleted(args)
    {
     //some actions when backgroundtask.Run() is done
    }
    
    //app activation
    IBackgroundTaskRegistration task;
    task = backgroundTask.register();
    task.addEventListener("completed", OnCompleted);


    But my background task runs not only Run() function. The task also creates timer and I want to push notification to the main app when timeout is occurred.

    Can I add any custom event object into background task? Then add listener for it (event) in the main app and push notification throw this event from the background task to the main app?

    I means something like this psevdo code:

    //C# background task
    namespace backgroundTask
    {
    	public sealed class NotificationTask : IBackgroundTask
    	{
    		//some Event object
    		public Event myEvent; 
    		//some timer object
    		private Timer timerObject;
    
    		//Run()
    		public void Run(IBackgroundTaskInstance taskInstance)
    		{
    			 //... tile updating 
    			 //... starting of the timer
    			 timerObject.start(timeout);
    		 }
    
    		//timeout()
    		private void timeout()
    		{
    		 //push notification to the main app throw myEvent
    		}
    	}
    }
    
    //main JavaScript app
    //app activation...
    var task = backgroundTask.NotificationTask.register();
    task.addEventListener("myevent", OnCompleted);




    • Edited by _dima Thursday, March 06, 2014 4:51 PM
    Thursday, March 06, 2014 4:49 PM