{"id":277,"date":"2017-11-05T09:42:10","date_gmt":"2017-11-05T14:42:10","guid":{"rendered":"http:\/\/blog.cubicleninja.com\/?p=277"},"modified":"2026-06-07T10:28:42","modified_gmt":"2026-06-07T15:28:42","slug":"xamarin-forms-background-tasks-with-messagingcenter","status":"publish","type":"post","link":"https:\/\/blog.cubicleninja.com\/?p=277","title":{"rendered":"Xamarin.Forms Background Tasks with MessagingCenter"},"content":{"rendered":"<p>When developing mobile applications, a common need is to be able to perform some task (long-running or otherwise) off the main thread and ensure that your main thread can respond appropriately when it completes.\u00a0 There are multiple ways to accomplish this sort of requirement, but I&#8217;m going to focus on how to handle it using the <a href=\"https:\/\/developer.xamarin.com\/guides\/xamarin-forms\/application-fundamentals\/messaging-center\/\" target=\"_blank\">MessagingCenter<\/a>.\u00a0 I covered a fairly simple &#8220;call and response&#8221; usage of MessagingCenter in my previous post for creating a\u00a0<a href=\"http:\/\/blog.cubicleninja.com\/?p=261\">Creating a Cross-Platform Soundboard<\/a>, this one will leverage similar concepts but take things a bit further.<\/p>\n<p>We\u2019ll start out in Visual Studio and create a project of type\u00a0<strong>Visual C#<\/strong>\u00a0-&gt;\u00a0<strong>Cross-Platform<\/strong>\u00a0-&gt;\u00a0<strong>Cross Platform App (Xamarin).<\/strong><\/p>\n<p><a href=\"http:\/\/blog.cubicleninja.com\/wp-content\/uploads\/2017\/11\/MessagingCenter1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-278\" src=\"http:\/\/blog.cubicleninja.com\/wp-content\/uploads\/2017\/11\/MessagingCenter1-300x300.png\" alt=\"MessagingCenter1\" width=\"300\" height=\"300\" \/><\/a><\/p>\n<p>On the next screen, select\u00a0<strong>Master Detail<\/strong> for the template and\u00a0<strong>Portable Class Library (PCL)<\/strong> for the Code Sharing Strategy.<\/p>\n<p><a href=\"http:\/\/blog.cubicleninja.com\/wp-content\/uploads\/2017\/11\/MessagingCenter2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-279\" src=\"http:\/\/blog.cubicleninja.com\/wp-content\/uploads\/2017\/11\/MessagingCenter2-300x254.png\" alt=\"MessagingCenter2\" width=\"300\" height=\"254\" \/><\/a><\/p>\n<p>Churn, churn, churn goes the Visual Studio for a bit and then you&#8217;ll be prompted to select the UWP targets, I&#8217;m just going to leave them set at their defaults and hit\u00a0<strong>OK<\/strong>.<\/p>\n<p>The\u00a0<strong>Master Detail<\/strong> template adds in several files to help you understand the MVVM concepts and starts you off with an application you can actually run to see how it all fits together.\u00a0 Feel free to play around a bit with that if you&#8217;d like, but for our purposes, we&#8217;re going to delete out all of the files that were auto-generated into the\u00a0<strong>Models<\/strong>,\u00a0<strong>Services, ViewModels, <\/strong>and<strong> Views<\/strong> folders.\u00a0 This should leave us with a\u00a0<strong>Portable\u00a0<\/strong>project\u00a0that looks something like this:<br \/>\n<a href=\"http:\/\/blog.cubicleninja.com\/wp-content\/uploads\/2017\/11\/MessagingCenter3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-280\" src=\"http:\/\/blog.cubicleninja.com\/wp-content\/uploads\/2017\/11\/MessagingCenter3-300x253.png\" alt=\"MessagingCenter3\" width=\"300\" height=\"253\" \/><\/a><\/p>\n<p>Now that we have a mostly clean project, we&#8217;ll begin building back up our sample application.\u00a0 Right-click on the\u00a0<strong>Helpers<\/strong> folder, select\u00a0<strong>Add -&gt; Class<\/strong> and give it a name of\u00a0<strong>MessagingCenterObject<\/strong>.\u00a0 In the new class file that opens, give the class a public accessor and add two public properties of type string:\u00a0\u00a0<strong>result<\/strong> and\u00a0<strong>message<\/strong>.<\/p>\n<pre class=\"lang:c# decode:true \">namespace MessagingCenterTest.Helpers\n{\n    public class MessagingCenterObject\n    {\n        public string result { get; set; }\n        public string message { get; set; }\n    }\n}\n<\/pre>\n<p>The next piece we want to add will be a ViewModel.\u00a0 Right-click on the\u00a0<strong>ViewModels<\/strong> folder and select\u00a0<strong>Add -&gt; Class<\/strong>.\u00a0 For the name of the class, put in\u00a0<strong>MainViewModel.cs<\/strong> and then click <strong>Add<\/strong>.<\/p>\n<p>Give your new class a public accessor and set it to inherit from\u00a0<strong>ObservableObject<\/strong> ( ObservableObject is a helper class that was added automagically for us by the template &#8212; you&#8217;ll need to add a using statement for the namespace to reference it &#8211; the reason we want to inherit from the ObservableObject is because it provides some base wiring that allows us to easily add binding properties that will update the UI when they are changed ).\u00a0 Add two public properties to the new\u00a0<strong>MainViewModel<\/strong> class named <strong>Title<\/strong> and\u00a0<strong>Label<\/strong>, both of type\u00a0<strong>string<\/strong> and make sure to use the\u00a0<strong>SetProperty<\/strong> helper for them.\u00a0 We also need a private <strong>MessagingCenterObject<\/strong> and a public\u00a0<strong>Command<\/strong>.\u00a0 \u00a0The\u00a0<strong>Command<\/strong> is what we will use with a button in our view to fire off a message.\u00a0 This ends up with a class that looks like this<\/p>\n<pre class=\"lang:c# decode:true\">using MessagingCenterTest.Helpers;\nusing Xamarin.Forms;\n\nnamespace MessagingCenterTest.ViewModels\n{\n    public class MainViewModel : ObservableObject\n    {\n        private MessagingCenterObject msgObj;\n        public Command ButtonCommand { get; set; }\n\n        private string _title;\n        public string Title\n        {\n            get { return _title; }\n            set { SetProperty(ref _title, value); }\n        }\n\n        private string _label;\n        public string Label\n        {\n            get { return _label; }\n            set { SetProperty(ref _label, value); }\n        }\n\n        public MainViewModel()\n        {\n            Title = \"Main View\";\n            Label = \"Waiting to Start\";\n            \/\/ Initialize our messaging center object\n            \/\/ it's blank for now because we don't need any parameters to the start\n            msgObj = new MessagingCenterObject();\n\n            \/\/ We set the Button command so that when it fires it sends a start message\n            \/\/ to the MessagingCenter\n            ButtonCommand = new Command(() =&gt;\n            {\n                MessagingCenter.Send&lt;MessagingCenterObject&gt;(msgObj, \"StartProcessing\");\n            });\n        }\n    }\n}\n<\/pre>\n<p>With the\u00a0<strong>ViewModel\u00a0<\/strong>prepared, right-click on the\u00a0<strong>Views<\/strong> folder and select\u00a0<strong>Add -&gt; New Item.\u00a0\u00a0<\/strong>From the template selection screen, select\u00a0<strong>Xamarin.Forms<\/strong> on the left, then the\u00a0<strong>XAML<\/strong> based\u00a0<strong>Content Page<\/strong> on the right, and give it a name of\u00a0<strong>MainView.xaml<\/strong><\/p>\n<p><a href=\"http:\/\/blog.cubicleninja.com\/wp-content\/uploads\/2017\/11\/MessagingCenter4.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-281\" src=\"http:\/\/blog.cubicleninja.com\/wp-content\/uploads\/2017\/11\/MessagingCenter4-252x300.png\" alt=\"MessagingCenter4\" width=\"252\" height=\"300\" \/><\/a><\/p>\n<p>For the view, we&#8217;ll use a simple\u00a0<strong>Grid<\/strong> with two rows, one for a text label and one for a button.<\/p>\n<pre class=\"lang:xhtml decode:true\">&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;ContentPage xmlns=\"http:\/\/xamarin.com\/schemas\/2014\/forms\"\n             xmlns:x=\"http:\/\/schemas.microsoft.com\/winfx\/2009\/xaml\"\n             xmlns:vm=\"clr-namespace:MessagingCenterTest.ViewModels\"\n             x:Class=\"MessagingCenterTest.Views.MainView\"\n             Title=\"{Binding Title}\"&gt;\n    &lt;!-- Make sure to add an XML namespace for your ViewModel namespace up above, mine is aliased to vm --&gt;\n    &lt;!-- Add in the BindingContext and wire it in to the MainViewModel we created earlier--&gt;\n    &lt;ContentPage.BindingContext&gt;\n        &lt;vm:MainViewModel&gt;&lt;\/vm:MainViewModel&gt;\n    &lt;\/ContentPage.BindingContext&gt;\n    &lt;ContentPage.Content&gt;\n        &lt;Grid&gt;\n            &lt;Grid.RowDefinitions&gt;\n                &lt;RowDefinition Height=\"*\"&gt;&lt;\/RowDefinition&gt;\n                &lt;RowDefinition Height=\"44\"&gt;&lt;\/RowDefinition&gt;\n            &lt;\/Grid.RowDefinitions&gt;\n            &lt;Grid.ColumnDefinitions&gt;\n                &lt;ColumnDefinition Width=\"*\"&gt;&lt;\/ColumnDefinition&gt;\n            &lt;\/Grid.ColumnDefinitions&gt;\n            &lt;!-- Set the text of the label to the Label property in our viewmodel --&gt;\n            &lt;Label Text=\"{Binding Label}\" Grid.Row=\"0\" Grid.Column=\"0\" HorizontalOptions=\"CenterAndExpand\" VerticalOptions=\"CenterAndExpand\" \/&gt;\n            &lt;!-- Set the button to fire our viewmodel ButtonCommand when it is clicked --&gt;\n            &lt;Button Text=\"Start Background\" Command=\"{Binding ButtonCommand}\"  Grid.Row=\"1\" Grid.Column=\"0\"&gt;&lt;\/Button&gt;\n        &lt;\/Grid&gt;\n    &lt;\/ContentPage.Content&gt;\n&lt;\/ContentPage&gt;<\/pre>\n<p>Before we go any further, we need to modify the\u00a0<strong>App.xaml.cs<\/strong> file to properly point to our new view.\u00a0 Open the file and change the code in the\u00a0<strong>SetMainPage()<\/strong> method to the following:<\/p>\n<pre class=\"lang:c# decode:true \">        public static void SetMainPage()\n        {\n            Current.MainPage = new MainView();\n        }<\/pre>\n<p>Right now, if you run the project, you will get a display that has a\u00a0label that displays &#8220;Waiting to Start&#8221; and a button.\u00a0 Clicking the button wouldn&#8217;t have any effect at this point because we are sending a message but no one is listening (sad, I know).\u00a0 Let&#8217;s provide something to listen and respond to the message.<\/p>\n<p>Right-click on the\u00a0<strong>Helpers<\/strong> folder, select\u00a0<strong>Add -&gt; Class,\u00a0<\/strong>and give the file a name of\u00a0<strong>BackgroundListener.cs<\/strong>.\u00a0 Modify the class so that it is\u00a0<strong>public<\/strong> and\u00a0<strong>static<\/strong>.\u00a0 We&#8217;ll need to do a few things in here to get it prepared properly:\u00a0 create a few static properties to help maintain state, provide a static method to initialize the class, and set up our MessagingCenter subscriptions.\u00a0 Our example is going to be very simplistic, the background process is just going to wait for a set period of time and then send a message back out saying it has completed a processing round.\u00a0 \u00a0In the real world, you could use this for things such as reaching out to a web service to periodically refresh data, polling for other application updates, etc.<\/p>\n<p>The code for the BackgroundListener class is below, it&#8217;s commented to explain what the different pieces are doing.<\/p>\n<pre class=\"lang:c# decode:true \">using System.Threading.Tasks;\nusing Xamarin.Forms;\n\nnamespace MessagingCenterTest.Helpers\n{\n    public static class BackgroundListener\n    {\n        \/\/ The MessagingCenterObject that we'll use for passing data back and forth\n        private static MessagingCenterObject msgObj;\n        \/\/ A simple int to keep track of how many loops we've done\n        private static int loopCount = 0;\n        \/\/ A boolean to keep track of whether or not we are already processing\n        private static bool processing = false;\n        \/\/ A boolean to keep track of whether or not we are already initialized\n        private static bool initialized = false;\n\n        public static void InitListener()\n        {\n            \/\/ Because we subscribe to events during the initialization, we want to ensure we don't initialize multiple times\n            if (!initialized)\n            {\n                initialized = true;\n\n                msgObj = new MessagingCenterObject();\n                loopCount = 0;\n                processing = false;\n\n                \/\/ When initialized, start listening for the \"StartProcessing\" message\n                MessagingCenter.Subscribe&lt;MessagingCenterObject&gt;(msgObj, \"StartProcessing\", async (sender) =&gt;\n                {\n                    \/\/ Only start processing if we aren't already doing so, this is to prevent feedback loops\n                    \/\/ from multiple starts\n                    if (!processing)\n                    {\n                        processing = true;\n                        loopCount = 0;\n                        await ProcessLoop();\n                    }\n                });\n\n                \/\/ When initialized, start listening for the \"ContinueProcessing\" message\n                MessagingCenter.Subscribe&lt;MessagingCenterObject&gt;(msgObj, \"ContinueProcessing\", async (sender) =&gt;\n                {\n                    await ProcessLoop();\n                });\n            }\n        }\n\n        private static async Task&lt;bool&gt; ProcessLoop()\n        {\n            \/\/ pause for 2 seconds before doing anything\n            await Task.Delay(2000);\n\n            \/\/ Set the message and result value of our MessagingCenterObject\n            msgObj.message = $\"Completed Processing Loop {++loopCount}\";\n            msgObj.result = \"Success\";\n\n            \/\/ Send our MessagingCenterObject back out into the world as a \"FinishedProcessing\" message\n            MessagingCenter.Send&lt;MessagingCenterObject&gt;(msgObj, \"FinishedProcessing\");\n\n            return true;\n        }\n    }\n}\n<\/pre>\n<p>Before testing this out, we have two more adjustments to make; we need to modify our\u00a0<strong>MainViewModel<\/strong> so that it subscribes to the\u00a0<strong>FinishedProcessing<\/strong> event and add a line to our\u00a0<strong>App.xaml.cs<\/strong> to spin up the\u00a0<strong>BackgroundListener.<\/strong><\/p>\n<p>Modify the\u00a0<strong>MainViewModel.cs<\/strong> file and add the following lines to the bottom of the\u00a0<strong>MainViewModel()<\/strong> public constructor<\/p>\n<pre class=\"lang:c# decode:true \">            \/\/ Subscribe to the \"FinishedProcessing\" Message\n            MessagingCenter.Subscribe&lt;MessagingCenterObject&gt;(msgObj, \"FinishedProcessing\", (sender) =&gt;\n            {\n                \/\/ Update the label based on the message received\n                Label = sender.message;\n\n                \/\/ Fire off a ContinueProcessing message to continue the communication\n                MessagingCenter.Send&lt;MessagingCenterObject&gt;(msgObj, \"ContinueProcessing\");\n            });<\/pre>\n<p>Finally, modify the\u00a0<strong>App.xaml.cs<\/strong> and change the public constructor to look like the following<\/p>\n<pre class=\"lang:c# decode:true \">        public App()\n        {\n            InitializeComponent();\n\n            \/\/ start up the backgroundlistener for the application\n            BackgroundListener.InitListener();\n\n            SetMainPage();\n        }<\/pre>\n<p>At this point, you can run the application on any of the platforms and be able to watch the call-and-response between your ViewModel and the background listener process.<\/p>\n<p>In the next post, I&#8217;ll go over some slightly more complex concepts with MessagingCenter such as handling messages across multiple views and how to properly unsubscribe from MessagingCenter events to ensure you keep your event stack clean.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>When developing mobile applications, a common need is to be able to perform some task (long-running or otherwise) off the main thread and ensure that your main thread can respond appropriately when it completes.\u00a0 There are multiple ways to accomplish this sort of requirement, but I&#8217;m going to focus on how to handle it using &hellip; <a href=\"https:\/\/blog.cubicleninja.com\/?p=277\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Xamarin.Forms Background Tasks with MessagingCenter&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4,6,9,10,12],"tags":[14,16,30,40,42],"class_list":["post-277","post","type-post","status-publish","format-standard","hentry","category-android","category-csharp","category-ios","category-mobile","category-uwp","category-xamarin","tag-android","tag-c","tag-ios","tag-uwp","tag-xamarin"],"_links":{"self":[{"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/posts\/277","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=277"}],"version-history":[{"count":1,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/posts\/277\/revisions"}],"predecessor-version":[{"id":21820,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/posts\/277\/revisions\/21820"}],"wp:attachment":[{"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=277"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=277"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=277"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}