<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Romasz.net</title>
	<atom:link href="http://www.romasz.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.romasz.net</link>
	<description>Casual Developer&#039;s Blog</description>
	<lastBuildDate>Mon, 09 Jun 2014 08:34:10 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=3.8.35</generator>
	<item>
		<title>How to add a BackgroundTask</title>
		<link>http://www.romasz.net/how-to-add-a-backgroundtask/</link>
		<comments>http://www.romasz.net/how-to-add-a-backgroundtask/#comments</comments>
		<pubDate>Sun, 08 Jun 2014 15:27:50 +0000</pubDate>
		<dc:creator><![CDATA[Romasz]]></dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[background-task]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[universal-apps]]></category>
		<category><![CDATA[windows-phone-8.1]]></category>
		<category><![CDATA[windows-runtime]]></category>

		<guid isPermaLink="false">http://www.romasz.net/?p=196</guid>
		<description><![CDATA[Here is a step by step tutorial about adding a sample BackgroundTask to your solution. The presented procedure is the same for: Windows Phone 8.1 Silverlight, Runtime and Windows Universal Apps. All the needed informaion you will also find at MSDN. What is a BackgroundTask? In short &#8211; it&#8217;s  a lightweight code that the OS run in the background. Its [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Here is a step by step tutorial about adding a sample <em>BackgroundTask</em> to your solution. The presented procedure is the same for: Windows Phone 8.1 Silverlight, Runtime and Windows Universal Apps. All the needed informaion you will also find <a title="Supporting your app with background tasks" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977056.aspx" target="_blank">at MSDN</a>.</p>
<p>What is a <em>BackgroundTask?</em> In short &#8211; it&#8217;s  a lightweight code that the OS run in the background. Its purpose can be various and it can nicely extend your App. In this example we would write an App for Windows Phone 8.1 Runtime (but as I&#8217;ve mentioned before the steps are the same for other platforms). We will write a <em>BackgroundTask</em>  that will send a <a title="Sending toast messages" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868266.aspx" target="_blank"><em>Toast message</em></a> from background. Where to start?</p>
<p>1. Fisrt we have to add a new RuntimeComponent to our solution. To do this, right click on your solution in <em>Solution explorer </em>window in Visual Studio. Then click <em>Add</em>, <em>New project&#8230;</em> and choose <em>Windows Runtime Component </em>(Pic. 1) - depending on your purpose it can be <em>portable or windows phone</em>.</p>
<div id="attachment_200" style="width: 991px" class="wp-caption aligncenter"><a href="http://www.romasz.net/wp-content/uploads/2014/06/addRuntimeComponent.jpg"><img class=" wp-image-200 " alt="Pic. 1 Add WinRT Component" src="http://www.romasz.net/wp-content/uploads/2014/06/addRuntimeComponent.jpg" width="981" height="554" /></a><p class="wp-caption-text">Pic. 1 Add WinRT Component</p></div>
<p>&nbsp;</p>
<div id="attachment_199" style="width: 203px" class="wp-caption alignright"><a href="http://www.romasz.net/wp-content/uploads/2014/06/addReference.jpg"><img class=" wp-image-199 " alt="Pic. 2 Add reference" src="http://www.romasz.net/wp-content/uploads/2014/06/addReference.jpg" width="193" height="267" /></a><p class="wp-caption-text">Pic. 2 Add reference</p></div>
<p>2. Once we have the new project added, we need to add a reference  (Pic. 2) to it in our main project in which we will register our <em>BackgroundTask</em> &#8211; without this step, our App will crash once we try to run the background code.</p>
<p>3. Here comes the time to define our <em>BackgroundTask</em>. Of course the purpose of it depends on our needs. Let our task inform the User that it is running &#8211; for this we will implement a <a title="Sending toast message" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868254.aspx" target="_blank"><em>Toast message</em></a>. We shall also remember that to make it work we need to set our App as <em>Toast capable</em> &#8211; open <em>Package.appxmanifest</em> file, chose <em>Application</em> tab, in section <em>Notifications</em> set App as toast capable. The simple code of our task can look like this:</p><pre class="crayon-plain-tag">namespace MyTask
{
    public sealed class FirstTask : IBackgroundTask
    {
        public 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(&quot;text&quot;);
            textElements[0].AppendChild(toastXml.CreateTextNode(&quot;My first Task - Yeah&quot;));
            textElements[1].AppendChild(toastXml.CreateTextNode(&quot;I'm a message from your background task!&quot;));
            ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
        }
    }
}</pre><p>What is imortant in the code above:</p>
<ul>
<li>we need to define a <span style="text-decoration: underline;">sealed</span> class that will implement <a title="IBackgroundTask interface" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.applicationmodel.background.ibackgroundtask.aspx" target="_blank"><em>IBackgroundTask</em></a> interface &#8211; which means that we will have to write a <span style="text-decoration: underline;">public void</span> <em>Run(IBackgroundTaskInstance taskInstance)</em> method, that will perform our background work.</li>
<li>the name of the class and the namespace are imortant as we will have to specify the <em>entry point </em>of our <em>BackgroundTask</em> (see next step)</li>
<li>our <em>Run</em> method can be <em>asynchronous</em>, in this case we will have to obtain a <a title="BackgroundTAskDefferal" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.applicationmodel.background.backgroundtaskdeferral.aspx" target="_blank"><em>BackgroundTaskDeferral</em> </a> by using a <a title="GetDeferral method" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.applicationmodel.background.ibackgroundtaskinstance.getdeferral.aspx" target="_blank"><em>taskInstance.GetDeferral()</em></a> method. This will inform the OS that our background task might continue to perform work after the <em>Run</em> method returns. We must only remember to call <a title="BackgroundTaskDeferral Complete method" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.applicationmodel.background.backgroundtaskdeferral.complete.aspx" target="_blank"><em>BackgroundTaskDeferral.Complete()</em></a> once we finish our job.</li>
</ul>
<p>4. Now is the time to declare the <em>entry point</em> of our background task. To do this we need to open <em>Package.appxmanifest</em> file, find <em>Declarations</em> tab, choose <em>BackgroundTask</em> in dropdown menu and click <em>Add</em>. We should see it defined in the list below. We must also decide the type of our <em>BackgroundTask</em> - if it will be invoked upon <em>System event, </em><em>Timer</em> or other. For the purpose of this example we will use <em>Timer</em> type &#8211; our task will be fired upon <em><a title="TimeTrigger event" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.applicationmodel.background.timetrigger.aspx" target="_blank">TimeTrigger </a></em>event. All this you can see in the picture 3.</p>
<div id="attachment_201" style="width: 615px" class="wp-caption aligncenter"><a href="http://www.romasz.net/wp-content/uploads/2014/06/declaration.jpg"><img class="wp-image-201 " alt="Pic. 3 Declarations" src="http://www.romasz.net/wp-content/uploads/2014/06/declaration.jpg" width="605" height="576" /></a><p class="wp-caption-text">Pic. 3 Declarations</p></div>
<p>5. The time has come to <a title="Registering the task" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj553413.aspx" target="_blank">register our <em>BackgroundTask</em>.</a> First we shall check if the task is already registered, to do this we can enumerate<a title="All registered tasks" href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.background.backgroundtaskregistration.alltasks" target="_blank"> <em>BackgroundTaskRegistration.AllTasks</em> </a>, for the sake of simplicity, once we have found our task, we will just return from the method. To register the task we will use <a title="BackgroundTaskBuilder class" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.applicationmodel.background.backgroundtaskbuilder.aspx" target="_blank"><em>BackgroundTaskBuilder</em> </a> - we will need to specify its <em>entry point</em> (the same as we had set in <em>Declarations)</em>, provide a name of the task, set the <em>Trigger</em> (that will fire our task) and optionally we can specify <a title="System Conditions" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.applicationmodel.background.systemcondition.aspx" target="_blank"><em>SystemCondition</em></a>. The sample code can look like this:</p><pre class="crayon-plain-tag">private async void RegisterBtn_Click(object sender, RoutedEventArgs e)
{
    string myTaskName = "FirstTask";

    // check if task is already registered
    foreach (var cur in BackgroundTaskRegistration.AllTasks)
        if (cur.Value.Name == myTaskName)
        {
            await (new MessageDialog("Task already registered")).ShowAsync();
            return;
        }

    // Windows Phone app must call this to use trigger types (see MSDN)
    await BackgroundExecutionManager.RequestAccessAsync();

    // register a new task
    BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = "First Task", TaskEntryPoint = "MyTask.FirstTask" };
    taskBuilder.SetTrigger(new TimeTrigger(15, true));
    BackgroundTaskRegistration myFirstTask = taskBuilder.Register();

    await (new MessageDialog("Task registered")).ShowAsync();
}</pre><p>In the code above, we have registered a task that will be <a title="Run task upon time trigger." href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977059.aspx" target="_blank">fired upon <em>TimeTrigger</em></a> event. Althought we have set its <em>freshness time</em> to 15 minutes, it <strong>doesn&#8217;t</strong> mean that it will be fired exacly after this time &#8211; OS has a build-in timer that runs background tasks in 30 minutes intervals on Windows Phone (15 minutes on Windows). We have also set the task as <em>OneShot,</em> which means that it will be fired once (not in 15-30 minute intervals).</p>
<p>Finally once we click the button (invoke the method), our <em>BackgroundTask</em> will be registered and it should be run after 15-30 minutes. But what to do to test it faster &#8211; do we, as developers, have to wait? No, there is quite an easy way to invoke the <em>BackgroundTask</em> earlier, upon demand. To do this we have to open the <em>Debug location</em> toolbar in Visual Studio, select our task from dropdown menu <em>Lifecycle events</em> (sometimes you may need to open the menu few times to refresh it) and once we click on the name it will be fired (Pic. 4).</p>
<div id="attachment_220" style="width: 733px" class="wp-caption aligncenter"><a href="http://www.romasz.net/wp-content/uploads/2014/06/fireEarlier.jpg"><img class=" wp-image-220 " alt="Pic. 4 Test the Task" src="http://www.romasz.net/wp-content/uploads/2014/06/fireEarlier.jpg" width="723" height="299" /></a><p class="wp-caption-text">Pic. 4 Test the Task</p></div>
<p>The complete working example you can download here &#8211; <a href="http://www.romasz.net/wp-content/uploads/2014/06/SimpleBackgrounsTask.zip">SimpleBackgrounsTask</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.romasz.net/how-to-add-a-backgroundtask/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to take a photo in Windows Runtime</title>
		<link>http://www.romasz.net/how-to-take-a-photo-in-windows-runtime/</link>
		<comments>http://www.romasz.net/how-to-take-a-photo-in-windows-runtime/#comments</comments>
		<pubDate>Sun, 18 May 2014 09:23:20 +0000</pubDate>
		<dc:creator><![CDATA[Romasz]]></dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[windows-phone-8.1]]></category>
		<category><![CDATA[windows-runtime]]></category>

		<guid isPermaLink="false">http://www.romasz.net/?p=178</guid>
		<description><![CDATA[In Windows Phone Silverlight (8.0 and 8.1) we can use Camera Capture Task to capture a picture using build-in camera. It&#8217;s quite easy and we don&#8217;t have to do much to make it work. When writing a Windows Runtime App , the situation it&#8217;s little different &#8211; we cannot use above Task as it doen&#8217;t exist [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In <em>Windows Phone Silverlight</em> (8.0 and 8.1) we can use <a title="Camera Capture Task" href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006(v=vs.105).aspx" target="_blank">Camera Capture Task</a> to capture a picture using build-in camera. It&#8217;s quite easy and we don&#8217;t have to do much to make it work.</p>
<p>When writing a <em>Windows Runtime</em><em> App</em> , the situation it&#8217;s little different &#8211; we cannot use above Task as it doen&#8217;t exist in the API. We will have to use <a title="MediaCapture class" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.media.capture.mediacapture.aspx" target="_blank">MediaCapture class</a>.</p>
<p>First what we have to do is to initialize the class &#8211; within this step we will also need to declare which camera we wish to use and set the resolution. The sample code can look like this:</p><pre class="crayon-plain-tag">private static async Task&lt;DeviceInformation&gt; GetCameraID(Windows.Devices.Enumeration.Panel desiredCamera)
{
    // get available devices for capturing pictures
    DeviceInformation deviceID = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture))
        .FirstOrDefault(x =&gt; x.EnclosureLocation != null &amp;&amp; x.EnclosureLocation.Panel == desiredCamera);

    if (deviceID != null) return deviceID;
    else throw new Exception(string.Format("Camera of type {0} doesn't exist.", desiredCamera));
}

async private void InitCameraBtn_Click(object sender, RoutedEventArgs e)
{
    var cameraID = await GetCameraID(Windows.Devices.Enumeration.Panel.Back);
    captureManager = new MediaCapture();

    await captureManager.InitializeAsync(new MediaCaptureInitializationSettings
        {
            StreamingCaptureMode = StreamingCaptureMode.Video,
            PhotoCaptureSource = PhotoCaptureSource.VideoPreview,
            AudioDeviceId = string.Empty,
            VideoDeviceId = cameraID.Id
        });

    var maxResolution = captureManager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo).Aggregate((i1, i2) =&gt; (i1 as VideoEncodingProperties).Width &gt; (i2 as VideoEncodingProperties).Width ? i1 : i2);
    await captureManager.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, maxResolution);
}</pre><p>&nbsp;</p>
<div id="attachment_184" style="width: 136px" class="wp-caption alignright"><a href="http://www.romasz.net/wp-content/uploads/2014/05/ImageStripes.jpg"><img class=" wp-image-184" title="Pic. 1. Image stripes" alt="Pic. 1. Image stripes" src="http://www.romasz.net/wp-content/uploads/2014/05/ImageStripes-225x300.jpg" width="126" height="168" /></a><p class="wp-caption-text">Pic. 1. Image stripes</p></div>
<p>Choosing camera device is quite obvious &#8211; most mobile devices nowadays have at least two cameras and we should pick one (on my Phone default is Front camera). The code above identifies the ID of Back camera and then initializes <em>MediaCapture</em> class with suitable properties. Why do we have to set the resolution after initialization? &#8211; there is probably a default one. Yes that&#8217;s right, but if we don&#8217;t set the proper resolution then our taken photo can suffer strange stripes on its sides (Pic. 1).</p>
<p>So we have our class initialized, it&#8217;s prepared to take photos, but it will be nice to see what we will be in our picture. Here comes <a title="CaptureElement class" href="http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.ui.xaml.controls.captureelement" target="_blank"><em>CaptureElement</em></a> class with help. Using it in XAML is very simple:</p><pre class="crayon-plain-tag">&lt;CaptureElement x:Name="capturePreview" Stretch="Uniform" Height="200" Width="300"/&gt;</pre><p>When we have it defined, then we can start previewing:</p><pre class="crayon-plain-tag">async private void StartPreviewBtn_Click(object sender, RoutedEventArgs e)
{
    // rotate to see preview vertically
    captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
    capturePreview.Source = captureManager;
    await captureManager.StartPreviewAsync();
}</pre><p>To stop it &#8211; just call <pre class="crayon-plain-tag">await captureManager.StopPreviewAsync(); </pre><br />
Finally when we can take our photo &#8211; the API enables to capture photo <a title="Capture to StorageFile" href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700836.aspx" target="_blank">to StorageFile</a>  or <a title="Capture to stream" href="http://msdn.microsoft.com/en-us/library/windows/apps/hh700840.aspx" target="_blank">to Stream</a>:</p><pre class="crayon-plain-tag">async private void TakePhotoBtn_Click(object sender, RoutedEventArgs e)
{
    // create a file
    StorageFile photoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myFirstPhoto.jpg", CreationCollisionOption.ReplaceExisting);

    // take a photo with choosen Encoding
    await captureManager.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoFile);

    // we can also take a photo to memory stream
    // InMemoryRandomAccessStream memStream = new InMemoryRandomAccessStream();
    // await captureManager.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpegXR(), memStream);

    // show a photo on screen
    BitmapImage bitmapToShow = new BitmapImage(new Uri(photoFile.Path));
    imagePreivew.Source = bitmapToShow;  // show image on screen inside Image control defined in XAML
}</pre><p>After invoking the method we should see the photo in <em>Image </em>control (of course if we had defined one).</p>
<p><strong>What is important</strong> &#8211; remember always to <em>Dispose() </em> your <em>MediaCapture</em> class, stop previewing and handle possible errors. Also protect the initializing method from being invoked few times at the same moment &#8211; it can hang your Phone or camera so that any other app won&#8217;t be able to use it.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.romasz.net/how-to-take-a-photo-in-windows-runtime/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Watch out for asynchronous events</title>
		<link>http://www.romasz.net/watch-out-for-asynchronous-events/</link>
		<comments>http://www.romasz.net/watch-out-for-asynchronous-events/#comments</comments>
		<pubDate>Thu, 10 Apr 2014 10:35:13 +0000</pubDate>
		<dc:creator><![CDATA[Romasz]]></dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[windows-phone-8]]></category>

		<guid isPermaLink="false">http://www.romasz.net/?p=77</guid>
		<description><![CDATA[This is the first post and it was inspired by the question on SO. To better describe the problem, let&#8217;s make a very simple App which will have three TextBoxes: [crayon-69e5a1340f617827018407/] &#160; The main task of our App is that it should update all three TextBoxes, depending on the user input. So in the code behind [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>This is the first post and it was inspired by <a title="StackOverflow question" href="http://stackoverflow.com/q/22944913/2681948" target="_blank">the question on SO</a>. To better describe the problem, let&#8217;s make a very simple App which will have three TextBoxes:</p><pre class="crayon-plain-tag">&lt;TextBox x:Name="FirstBox" InputScope="Number" Grid.Row="0"/&gt; 
&lt;TextBox x:Name="SecondBox" InputScope="Number" Grid.Row="1"/&gt; 
&lt;TextBox x:Name="ThirdBox" InputScope="Number" Grid.Row="2"/&gt;</pre><p><div id="attachment_94" style="width: 210px" class="wp-caption alignright"><a href="http://www.romasz.net/wp-content/uploads/2014/04/Pic1.jpg"><img class="wp-image-94 " style="width: 172px; height: 160px;" title="Picture 1 Overlook" alt="Overlook" src="http://www.romasz.net/wp-content/uploads/2014/04/Pic1-300x261.jpg" width="200" height="200" /></a><p class="wp-caption-text">Pic. 1 Overlook</p></div></p>
<p>&nbsp;</p>
<p>The main task of our App is that it should update all three TextBoxes, depending on the user input. So in the code behind we will create an event handler and subscribe it to <em>TextBox.TextChanged</em> event (in this simple example I&#8217;ll just put the text informing which TextBox was changed):</p><pre class="crayon-plain-tag">public MainPage()
{
   InitializeComponent();
   FirstBox.TextChanged += Box_ChangedOne;
   SecondBox.TextChanged += Box_ChangedOne;
   ThirdBox.TextChanged += Box_ChangedOne;
}
private string info = "";
private void Box_ChangedOne(object sender, TextChangedEventArgs e)
{
    TextBox modifedTextBox = sender as TextBox;
    if (modifedTextBox.Name == "FirstBox") info = "User modified FirstBox";
    else if (modifedTextBox.Name == "SecondBox") info = "User modified SecondBox";
    else if (modifedTextBox.Name == "ThirdBox") info = "User modified ThirdBox";
    FirstBox.Text = info; // this line fires next Box_ChangedOne event
    SecondBox.Text = info; // this line fires next Box_ChangedOne event
    ThirdBox.Text = info; // this line fires next Box_ChangedOne event
}</pre><p>As you can see, I&#8217;ve subscribed <em>Box_ChangedOne</em> to all three TextBoxes  &#8211; let&#8217;s update everything right after one of them changes (why not?). Here comes the first problem, just after we focus on any control and try to put text &#8211; our App hangs. Aha &#8211; longer look at the code and it turns out that we are in an infinite loop &#8211; our event fires another one (cause it is changing TextBox.Text) and so on.  So we will improve the event handler with a flag which will inform if the change was invoked by user or from the code:</p><pre class="crayon-plain-tag">private bool dontChangeFlag = false;
private void Box_ChangedTwo(object sender, TextChangedEventArgs e)
{
    if (!dontChangeFlag)
    {
        TextBox modifedTextBox = sender as TextBox;
        if (modifedTextBox.Name == "FirstBox") info = "User modified FirstBox";
        else if (modifedTextBox.Name == "SecondBox") info = "User modified SecondBox";
        else if (modifedTextBox.Name == "ThirdBox") info = "User modified ThirdBox";
        dontChangeFlag = true; // set the flag to prevent next fired event from further changing Boxes
        FirstBox.Text = info;
        SecondBox.Text = info;
        ThirdBox.Text = info;
        dontChangeFlag = false; // enable changing
    }
}</pre><p>Looks great, so we should test it. Oops, the program hangs &#8211; what is wrong? The solution comes with <a title="TextBox.TextChanged" href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.windows.controls.textbox.textchanged%28v=vs.105%29.aspx">the MSDN</a>: <span style="text-decoration: underline;">The TextChanged event is asynchronous</span>. Our simple code is racy, and line <pre class="crayon-plain-tag">dontChangeFlag = false;</pre> is fired before the events &#8211; so we are again in an infinite loop. So why not delay a little our process and wait for other events to finish?</p><pre class="crayon-plain-tag">private async void Box_ChangedThree(object sender, TextChangedEventArgs e)
{
    if (!dontChangeFlag)
    {
        TextBox modifedTextBox = sender as TextBox;
        if (modifedTextBox.Name == "FirstBox") info = "User modified FirstBox";
        else if (modifedTextBox.Name == "SecondBox") info = "User modified SecondBox";
        else if (modifedTextBox.Name == "ThirdBox") info = "User modified ThirdBox";
        dontChangeFlag = true; // set the flag to prevent next fired event from further changing Boxes
        FirstBox.Text = info;
        SecondBox.Text = info;
        ThirdBox.Text = info;
        await Task.Delay(1000); // let's give some time to change Boxes
        dontChangeFlag = false; // enable changing
    }
}</pre><p>This time we get what we wanted &#8211; our flag is working. So far so good &#8211; but how to predict how long will it take the phone to finish the events? The answer is &#8211; we can&#8217;t and don&#8217;t do it &#8211; let the event informs when it is finished. For this purpose I&#8217;ll use a <em>SemaphoreSlim</em> class. And here we will also improve our code (to show the next issue) &#8211; our first TextBox will be set up with the entered text:</p><pre class="crayon-plain-tag">private string enteredText = "";
private SemaphoreSlim semWait = new SemaphoreSlim(0, 1);
private async void Box_ChangedFour(object sender, TextChangedEventArgs e)
{
    if (!dontChangeFlag)
    {
        TextBox modifedTextBox = sender as TextBox;
        if (modifedTextBox.Name == "FirstBox")
        {
            info = "User modified FirstBox";
            enteredText = FirstBox.Text;
        }
        else if (modifedTextBox.Name == "SecondBox") info = "User modified SecondBox";
        else if (modifedTextBox.Name == "ThirdBox") info = "User modified ThirdBox";
        dontChangeFlag = true; // set the lag to prevent next fired event from further changing Boxes
        FirstBox.Text = enteredText;
        await semWait.WaitAsync(); // wait until finished changing
        SecondBox.Text = info;
        await semWait.WaitAsync(); // wait until finished changing
        ThirdBox.Text = info;
        await semWait.WaitAsync(); // wait until finished changing
        dontChangeFlag = false; // enable changing
    }
    else semWait.Release();
}</pre><p>Our semaphore should wait until it is released, and it does so, but if we just change the text in the FirstBox then we will see that something is worng &#8211; there is no change in other TextBoxes. Quick debug shows that the semaphore waits to be released &#8211; what is wrong? Again qucik look at MSDN shows what is going on &#8211; <span style="text-decoration: underline;">If the Text property is set to the same string as the content in the TextBox, the event is not raised</span>.<span style="color: #000000;"> The simpliest way will be to check if the event is going to run:</span></p><pre class="crayon-plain-tag">private async void Box_ChangedFive(object sender, TextChangedEventArgs e)
{
    if (!dontChangeFlag)
    {
        TextBox modifedTextBox = sender as TextBox;
        if (modifedTextBox.Name == "FirstBox")
        {
            info = "User modified FirstBox";
            enteredText = FirstBox.Text;
        }
        else if (modifedTextBox.Name == "SecondBox") info = "User modified SecondBox";
        else if (modifedTextBox.Name == "ThirdBox") info = "User modified ThirdBox";
        dontChangeFlag = true; // set the lag to prevent next fired event from further changing Boxes
        if (FirstBox.Text != enteredText)
        {
            FirstBox.Text = info;
            await semWait.WaitAsync(); // wait until finished changing
        }
        if (SecondBox.Text != info)
        {
            SecondBox.Text = info;
            await semWait.WaitAsync(); // wait until finished changing
        }
        if (ThirdBox.Text != info)
        {
            ThirdBox.Text = info;
            await semWait.WaitAsync(); // wait until finished changing
        }
    }
    else semWait.Release();
}</pre><p>Finally our code is working as it should.</p>
<p>One may ask &#8211; what is the purpose of the slider in the picture? This is a simple test showing that not every event is run asynchronous &#8211; if we write a similar method like above, but for Slider&#8217;s change:</p><pre class="crayon-plain-tag">private void mySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs&lt;double&gt; e)
{
    if (!dontChangeFlag)
    {
        dontChangeFlag = true;
        mySlider.Value = 50;
        // below process continues after the second   
        // mySlider_ValueChanged has finished its job
        dontChangeFlag = false;
    }
}</pre><p>and set up breakpoints at lines 3 and 9, then we will see in debug mode that everything works <em>synchronously.</em></p>
<p><strong>Conclusion: </strong>Even if think that you write your code as <em>synchronous</em>, some events/methods can be run as <em>asynchronous, </em>so it&#8217;s worth to check them in the documentation.</p>
<p>Complete working example you can <a href="http://www.romasz.net/wp-content/uploads/2014/03/WatchOutAsyncEvent.zip">download from here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.romasz.net/watch-out-for-asynchronous-events/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
