<?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>Download Free medical and engineering ebooks&#187; .NET Help</title>
	<atom:link href="http://www.feedpals.com/category/net-help/feed" rel="self" type="application/rss+xml" />
	<link>http://www.feedpals.com</link>
	<description>Free medical, engineering, programming java, JSP , graphics ebooks, books, rapidshare, megaupload, sharing</description>
	<lastBuildDate>Sun, 05 Feb 2012 07:32:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>APRESS BEGINNING PHP AND MYSQL 5: FROM NOVICE TO PROFESSIONAL</title>
		<link>http://www.feedpals.com/apress-beginning-php-and-mysql-5-from-novice-to-professional.html</link>
		<comments>http://www.feedpals.com/apress-beginning-php-and-mysql-5-from-novice-to-professional.html#comments</comments>
		<pubDate>Fri, 20 May 2011 10:13:48 +0000</pubDate>
		<dc:creator>Shahid Siddique</dc:creator>
				<category><![CDATA[.NET Help]]></category>
		<category><![CDATA[beginnig php books]]></category>

	<!-- AutoMeta Start -->
	<category></category>
	<category></category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://www.feedpals.com/?p=40412</guid>
		<description><![CDATA[Written for the budding scheme developer intelligent for a powerful, low-cost resolution for antiquity flexible, impulsive scheme sites. Essentially threesome books in one: provides complete introductions to the PHP module and the MySQL database, and shows you how these digit technologies crapper be effectively desegrated to physique coercive websites. Provides over 500 cipher examples, including [...]]]></description>
			<content:encoded><![CDATA[<p>Written for the budding scheme developer intelligent for a powerful, low-cost resolution for antiquity flexible, impulsive scheme sites.<br />
Essentially  threesome books in one: provides complete introductions to the PHP module  and the MySQL database, and shows you how these digit technologies crapper be  effectively desegrated to physique coercive websites.</p>
<p>Provides over  500 cipher examples, including real-world tasks much as creating an  auto-login feature, sending HTML-formatted e-mail, investigating countersign  guessability, and uploading files via a scheme interface.<br />
Updated for MySQL 5, includes newborn chapters introducing triggers, stored procedures, and views.</p>
<p>From the Back Cover<br />
Interested  in decent a officer of the PHP module and MySQL database but don’t  undergo where to begin? This best-selling aggregation ranks among the most  complete and applicatory guides in print, concealment every of the key concepts  and features, and display you how to effectively combine PHP and  MySQL to physique coercive scheme sites.</p>
<p>The aggregation begins with a vast  overview of PHP’s capabilities, play with a analyse of the  artefact and plan impact on both the Windows and UNIX  platforms. Next, individual chapters are devoted to base PHP concepts,  including variables, datatypes, arrays, functions, progress manipulation,  and processing individual input. Other key PHP topics are also covered,  including PEAR, conference handling, LDAP integration, the Smarty  templating engine, Web services, and PDO.</p>
<p>Next up is a  show of MySQL’s key features. You’re prototypal guided finished  MySQL’s artefact and plan process, and are presented with  an launching to its hardware engines, datatypes, brass  utilities, section features, and accumulation import/export facilities. New  MySQL 5–specific chapters hit been additional in this edition, concealment  triggers, stored procedures, and views. Along the way, you’ll acquire  brainwave into PHP’s miscellanea of MySQL functions (using both the mysql  and mysqli extensions), and see how to create and fulfil queries,  action searches, and circularize discover key database tasks from within your Web  application.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.feedpals.com/apress-beginning-php-and-mysql-5-from-novice-to-professional.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AWAIT ANYTHING;</title>
		<link>http://www.feedpals.com/await-anything.html</link>
		<comments>http://www.feedpals.com/await-anything.html#comments</comments>
		<pubDate>Fri, 14 Jan 2011 05:33:26 +0000</pubDate>
		<dc:creator></dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/shahidsi/public_html/feedpals.com/wp-content/plugins/autometa/autometa.php</b> on line <b>300</b><br />
		<category><![CDATA[.NET Help]]></category>
		<category><![CDATA[ctp]]></category>
		<category><![CDATA[parallel-extensions]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://www.feedpals.com/await-anything.html</guid>
		<description><![CDATA[ One of the very cool things about the new await keyword in C# and Visual Basic is that it’s pattern based.&#160; It works great with Task and Task&#60;TResult&#62;, and awaiting those two types will represent the vast majority of uses, but they’re by no means the only types that can be awaited.&#160; The languages support awaiting any instance that exposes the right method (either instance method or extension method): GetAwaiter.&#160; A GetAwaiter needs to return a type that itself exposes two methods (again, either instance or extension): bool BeginAwait(Action); TResult EndAwait(); // TResult can also be void As an example of this, in the Async CTP, Task’s GetAwaiter method returns a value of type TaskAwaiter: public struct TaskAwaiter { &#160;&#160;&#160; public bool BeginAwait(Action continuation); &#160;&#160;&#160; public void EndAwait(); } and that’s what enables awaiting the Task.&#160; This is a simplification, but in short the BeginAwait method registers the Action as a continuation onto the Task (e.g. with ContinueWith), such that when the task completes, it will cause the compiler-generated state machine around the await to pick back up where it left off. The title of this post is “await anything;”, so let’s see how we can await things besides Task and Task&#60;TResult&#62;.&#160; To do that, we’ll need appropriate “awaiter” types for the “awaitable” type to await.&#160; That doesn’t mean we have to write new “awaiter” types, however.&#160; There are really two different approaches to making something awaitable: develop a new awaiter type that exposes the right pattern, or figure out how to create a Task or Task&#60;TResult&#62; from the thing being awaited, and then just reuse Task or Task&#60;TResult&#62;’s awaiter.&#160; For the majority of cases, the latter approach is very straightforward, so we’ll start with that. Let’s say you want to be able to write code like: await TimeSpan.FromMinutes(15); in order to asynchronously pause for 15 minutes.&#160; To do that, we can develop a 1-line GetAwaiter method for TimeSpan: public static TaskAwaiter GetAwaiter(this TimeSpan timeSpan) { &#160;&#160;&#160; return TaskEx.Delay(timeSpan).GetAwaiter(); } That’s it.&#160; Or let’s say we like waiting for periods of time so much, that we want to simply this down to just: await 15000; // in milliseconds No problem, we can do that with another one-line awaiter: public static TaskAwaiter GetAwaiter(this Int32 millisecondsDue) { &#160;&#160;&#160; return TimeSpan.FromMilliseconds(millisecondsDue).GetAwaiter(); } Let’s say we like waiting for time-like things so much that we want to be able to wait until a particular date/time, ala await DateTimeOffset.UtcNow.AddMinutes(1); Again, piece of cake: public static TaskAwaiter GetAwaiter(this DateTimeOffset dateTimeOffset) { &#160;&#160;&#160; return (dateTimeOffset - DateTimeOffset.UtcNow).GetAwaiter(); } Tired of time?&#160; Alright.&#160; The GetAwaiter function for Task allows you to wait for a single task, how about enabling waiting for an enumerable of tasks so that you can write code like: await from url in urls select DownloadAsync(url); Easy peasy: public static TaskAwaiter GetAwaiter(this IEnumerable&#60;Task&#62; tasks) { &#160;&#160;&#160; return TaskEx.WhenAll(tasks).GetAwaiter(); } All of the examples thus far were one-liners because we already have a function that takes the input to the extension method and produces a task from it.&#160; However, with just a few more lines, you can convert almost anything that has some notion of future completion into a task, through the TaskCompletionSource&#60;TResult&#62; type.&#160; If you can express your need by completing the statement “I want to await until …” or “I want to the await to complete when …”, this is likely a good approach for you. As an example, consider wanting to spin up another process and then asynchronously wait for that process to complete, e.g. await Process.Start(“Foo.exe”); You could do that with a GetAwaiter method like the following: public static TaskAwaiter&#60;int&#62; GetAwaiter(this Process process) { &#160;&#160;&#160; var tcs = new TaskCompletionSource&#60;int&#62;(); &#160;&#160;&#160; process.EnableRaisingEvents = true; &#160;&#160;&#160; process.Exited += (s, e) =&#62; tcs.SetResult(process.ExitCode); &#160;&#160;&#160; if (process.HasExited) tcs.SetResult(process.ExitCode); &#160;&#160;&#160; return tcs.Task.GetAwaiter(); } Or maybe you want to asynchronously wait until cancellation is requested, e.g. await cancellationToken; That could be done with a GetAwaiter like the following: public static TaskAwaiter GetAwaiter(this CancellationToken cancellationToken) { &#160;&#160;&#160; var tcs = new TaskCompletionSource&#60;bool&#62;(); &#160;&#160;&#160; Task t = tcs.Task; &#160;&#160;&#160; if (cancellationToken.IsCancellationRequested) tcs.SetResult(true); &#160;&#160;&#160; else cancellationToken.Register(s =&#62; ((TaskCompletionSource&#60;bool&#62;)s).SetResult(true), tcs); &#160;&#160;&#160; return t.GetAwaiter(); } You get the idea. The second approach to making an awaitable type is to implement a custom awaiter.&#160; This could either be a separate type that’s returned by GetAwaiter and that exposes the BeginAwait/EndAwait methods, or it could be a GetAwaiter method that returns “this”, with BeginAwait and EndAwait also exposed on the awaitable type.&#160; You’d typically go this route if you can’t express your desire as “I want the await to complete when…”, but rather as “When the await completes, I want to continue executing …”, filling in the blank for that “…”.&#160; In particular, you’d need to use this approach if you need full control over how (rather than when) the “Action continuation” delegate is invoked. Imagine, for example, that you wanted to launch some work to run on the ThreadPool.&#160; This work would compute a string and then store the result into a control on your UI.&#160; To modify the control, you need to be on the UI thread, so you somehow need to transition to the UI thread to do that work.&#160; If this were, for example, a Windows Forms application, we could accomplish this by building an awaiter for a Windows Forms Control.&#160; That would allow us to write code like: ThreadPool.QueueUserWorkItem(async delegate { &#160;&#160;&#160; string text = ComputeString(); &#160;&#160;&#160; await button1; &#160;&#160;&#160; button1.Text = text; }); We want the operation of awaiting the button1 to transition to the UI thread and then continue the execution there.&#160; We can do that with an implementation like the following: public static ControlAwaiter GetAwaiter(this Control control) { &#160;&#160;&#160; return new ControlAwaiter(control); } public struct ControlAwaiter { &#160;&#160;&#160; private readonly Control m_control; &#160;&#160;&#160; public ControlAwaiter(Control control) &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; if (control == null) throw new ArgumentNullException(&#34;control&#34;); &#160;&#160;&#160;&#160;&#160;&#160;&#160; m_control = control; &#160;&#160;&#160; } &#160;&#160;&#160; public bool BeginAwait(Action continuation) &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; if (m_control == null) throw new InvalidOperationException(); &#160;&#160;&#160;&#160;&#160;&#160;&#160; if (!m_control.InvokeRequired) return false; &#160;&#160;&#160;&#160;&#160;&#160;&#160; m_control.BeginInvoke(continuation); &#160;&#160;&#160;&#160;&#160;&#160;&#160; return true; &#160;&#160;&#160; } &#160;&#160;&#160; public void EndAwait() { } } You can also combine these approaches, such as by writing a custom awaiter which wraps the awaiter for a task, layering on additional functionality.&#160; For example, culture information is not flowed by default as part of ExecutionContext, which is the standard .NET mechanism for transferring important environmental information across asynchronous invocations.&#160; What if we wanted to make it easy to flow culture?&#160; Imagine the following syntax for awaiting a task with the flow of culture: await task.WithCulture(); We could enable that with code like the following: public static CultureAwaiter WithCurrentCulture(this Task task) { &#160;&#160;&#160; return new CultureAwaiter(task); } public class CultureAwaiter { &#160;&#160;&#160; private readonly TaskAwaiter m_awaiter; &#160;&#160;&#160; private CultureInfo m_culture; &#160;&#160;&#160; public CultureAwaiter(Task task) &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; if (task == null) throw new ArgumentNullException(&#34;task&#34;); &#160;&#160;&#160;&#160;&#160;&#160;&#160; m_awaiter = task.GetAwaiter(); &#160;&#160;&#160; } &#160;&#160;&#160; public CultureAwaiter GetAwaiter() { return this; } &#160;&#160;&#160; public bool BeginAwait(Action continuation) &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; m_culture = Thread.CurrentThread.CurentCulture; &#160;&#160;&#160;&#160;&#160;&#160;&#160; return m_awaiter.BeginAwait(continuation); &#160;&#160;&#160; } &#160;&#160;&#160; public void EndAwait() &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; Thread.CurrentThread.CurrentCulture = m_culture; &#160;&#160;&#160;&#160;&#160;&#160;&#160; m_awaiter.EndAwait(); &#160;&#160;&#160; } } This awaiter implementation wraps a TaskAwaiter, and this implementations BeginAwait and EndAwait methods delegate to the contained TaskAwaiter’s.&#160; On top of that, though, the implementation captures the current culture in BeginAwait and then restores it in EndAwait. By now, it should be obvious that there are loads of interesting possibilities here.&#160; I look forward to seeing all the interesting and useful awaiters you come up with.&#160; Just keep in mind that while there are plenty of “cool” things you can do, code readability and maintainability is really important, so make sure that the coolness isn’t trumped by lack of clarity about the code’s meaning. ]]></description>
			<content:encoded><![CDATA[<p>
<p>One of the rattling add things most the newborn await keyword in C# and Visual Basic is that it’s ornament based.&#160; It entireness enthusiastic with Task and Task&lt;TResult&gt;, and awaiting those digit types module equal the vast eld of uses, but they’re by no effectuation the exclusive types that crapper be awaited.&#160; The languages hold awaiting whatever happening that exposes the correct method (either happening method or spreading method): GetAwaiter.&#160; A GetAwaiter needs to convey a identify that itself exposes digit methods (again, either happening or extension):</p>
<blockquote><p>bool BeginAwait(Action);        <br />TResult EndAwait(); // TResult crapper also be void</p>
</blockquote>
<p>As an warning of this, in the Async CTP, Task’s GetAwaiter method returns a continuance of identify TaskAwaiter:</p>
<blockquote><p>public struct TaskAwaiter        <br />{         <br />&#160;&#160;&#160; open bool BeginAwait(Action continuation);         <br />&#160;&#160;&#160; open vacuum EndAwait();         <br />}</p>
</blockquote>
<p>and that’s what enables awaiting the Task.&#160; This is a simplification, but in brief the BeginAwait method registers the Action as a postscript onto the Task (e.g. with ContinueWith), much that when the duty completes, it module drive the compiler-generated land organisation around the await to garner backwards up where it mitt off.</p>
<p>The denomination of this place is “await anything;”, so let’s wager how we crapper await things likewise Task and Task&lt;TResult&gt;.&#160; To do that, we’ll requirement pertinent “awaiter” types for the “awaitable” identify to await.&#160; That doesn’t stingy we hit to indite newborn “awaiter” types, however.&#160; There are rattling digit assorted approaches to making something awaitable: amend a newborn awaiter identify that exposes the correct pattern, or amount discover how to create a Task or Task&lt;TResult&gt; from the abstract existence awaited, and then meet reuse Task or Task&lt;TResult&gt;’s awaiter.&#160; For the eld of cases, the latter move is rattling straightforward, so we’ll move with that.</p>
<p>Let’s feature you poverty to be healthy to indite cipher like:</p>
<blockquote><p>await TimeSpan.FromMinutes(15);</p>
</blockquote>
<p>in visit to asynchronously disrupt for 15 minutes.&#160; To do that, we crapper amend a 1-line GetAwaiter method for TimeSpan:</p>
<blockquote><p>public noise TaskAwaiter GetAwaiter(this TimeSpan timeSpan)        <br />{         <br />&#160;&#160;&#160; convey TaskEx.Delay(timeSpan).GetAwaiter();         <br />}</p>
</blockquote>
<p>That’s it.&#160; Or let’s feature we same inactivity for periods of instance so much, that we poverty to only this downbound to just:</p>
<blockquote><p>await 15000; // in milliseconds</p>
</blockquote>
<p>No problem, we crapper do that with added one-line awaiter:</p>
<blockquote><p>public noise TaskAwaiter GetAwaiter(this Int32 millisecondsDue)        <br />{         <br />&#160;&#160;&#160; convey TimeSpan.FromMilliseconds(millisecondsDue).GetAwaiter();         <br />}</p>
</blockquote>
<p>Let’s feature we same inactivity for time-like things so much that we poverty to be healthy to move until a portion date/time, ala</p>
<blockquote><p>await DateTimeOffset.UtcNow.AddMinutes(1);</p>
</blockquote>
<p>Again, warning of cake:</p>
<blockquote><p>public noise TaskAwaiter GetAwaiter(this DateTimeOffset dateTimeOffset)        <br />{         <br />&#160;&#160;&#160; convey (dateTimeOffset &#8211; DateTimeOffset.UtcNow).GetAwaiter();         <br />}</p>
</blockquote>
<p>Tired of time?&#160; Alright.&#160; The GetAwaiter duty for Task allows you to move for a azygos task, how most sanctioning inactivity for an enumerable of tasks so that you crapper indite cipher like:</p>
<blockquote><p>await from url in urls superior DownloadAsync(url);</p>
</blockquote>
<p>Easy peasy:</p>
<blockquote><p>public noise TaskAwaiter GetAwaiter(this IEnumerable&lt;Task&gt; tasks)        <br />{         <br />&#160;&#160;&#160; convey TaskEx.WhenAll(tasks).GetAwaiter();         <br />}</p>
</blockquote>
<p>All of the examples thusly farther were one-liners because we already hit a duty that takes the signaling to the spreading method and produces a duty from it.&#160; However, with meet a whatever more lines, you crapper add nearly anything that has whatever intent of forthcoming termination into a task, finished the TaskCompletionSource&lt;TResult&gt; type.&#160; If you crapper impart your requirement by completing the evidence “I poverty to await until …” or “I poverty to the await to rank when …”, this is probable a beatific move for you.</p>
<p>As an example, study wanting to aerobatics up added impact and then asynchronously move for that impact to complete, e.g.</p>
<blockquote><p>await Process.Start(“Foo.exe”);</p>
</blockquote>
<p>You could do that with a GetAwaiter method same the following:</p>
<blockquote><p>public noise TaskAwaiter&lt;int&gt; GetAwaiter(this Process process)        <br />{         <br />&#160;&#160;&#160; var tcs = newborn TaskCompletionSource&lt;int&gt;();         <br />&#160;&#160;&#160; process.EnableRaisingEvents = true;         <br />&#160;&#160;&#160; process.Exited += (s, e) =&gt; tcs.SetResult(process.ExitCode);         <br />&#160;&#160;&#160; if (process.HasExited) tcs.SetResult(process.ExitCode);         <br />&#160;&#160;&#160; convey tcs.Task.GetAwaiter();         <br />}</p>
</blockquote>
<p>Or maybe you poverty to asynchronously move until cancellation is requested, e.g.</p>
<blockquote><p>await cancellationToken;</p>
</blockquote>
<p>That could be finished with a GetAwaiter same the following:</p>
<blockquote><p>public noise TaskAwaiter GetAwaiter(this CancellationToken cancellationToken)        <br />{         <br />&#160;&#160;&#160; var tcs = newborn TaskCompletionSource&lt;bool&gt;();         <br />&#160;&#160;&#160; Task t = tcs.Task;         <br />&#160;&#160;&#160; if (cancellationToken.IsCancellationRequested) tcs.SetResult(true);         <br />&#160;&#160;&#160; added cancellationToken.Register(s =&gt; ((TaskCompletionSource&lt;bool&gt;)s).SetResult(true), tcs);         <br />&#160;&#160;&#160; convey t.GetAwaiter();         <br />}</p>
</blockquote>
<p>You intend the idea.</p>
<p>The ordinal move to making an awaitable identify is to compel a bespoken awaiter.&#160; This could either be a removed identify that’s returned by GetAwaiter and that exposes the BeginAwait/EndAwait methods, or it could be a GetAwaiter method that returns “this”, with BeginAwait and EndAwait also unclothed on the awaitable type.&#160; You’d typically go this line if you can’t impart your poverty as “I poverty the await to rank when…”, but kinda as “When the await completes, I poverty to move executing …”, stuff in the grapheme for that “…”.&#160; In particular, you’d requirement to ingest this move if you requirement flooded curb over how (rather than when) the “Action continuation” assign is invoked.</p>
<p>Imagine, for example, that you desired to start whatever impact to separate on the ThreadPool.&#160; This impact would compute a progress and then accumulation the termination into a curb on your UI.&#160; To add the control, you requirement to be on the UI thread, so you someways requirement to transformation to the UI arrange to do that work.&#160; If this were, for example, a Windows Forms application, we could fulfill this by antiquity an awaiter for a Windows Forms Control.&#160; That would earmark us to indite cipher like:</p>
<blockquote><p>ThreadPool.QueueUserWorkItem(async assign        <br />{         <br />&#160;&#160;&#160; progress book = ComputeString();         <br />&#160;&#160;&#160; await button1;         <br />&#160;&#160;&#160; button1.Text = text;         <br />});</p>
</blockquote>
<p>We poverty the activeness of awaiting the button1 to transformation to the UI arrange and then move the enforcement there.&#160; We crapper do that with an feat same the following:</p>
<blockquote><p>public noise ControlAwaiter GetAwaiter(this Control control)        <br />{         <br />&#160;&#160;&#160; convey newborn ControlAwaiter(control);         <br />}</p>
<p>public struct ControlAwaiter        <br />{         <br />&#160;&#160;&#160; clannish readonly Control m_control;</p>
<p>&#160;&#160;&#160; open ControlAwaiter(Control control)        <br />&#160;&#160;&#160; {         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (control == null) intercommunicate newborn ArgumentNullException(&quot;control&quot;);         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_control = control;         <br />&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160; open bool BeginAwait(Action continuation)        <br />&#160;&#160;&#160; {         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (m_control == null) intercommunicate newborn InvalidOperationException();         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (!m_control.InvokeRequired) convey false;         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_control.BeginInvoke(continuation);         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; convey true;         <br />&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160; open vacuum EndAwait() { }        <br />}</p>
</blockquote>
<p>You crapper also consortium these approaches, much as by composition a bespoken awaiter which wraps the awaiter for a task, layering on added functionality.&#160; For example, society aggregation is not flowed by choice as conception of ExecutionContext, which is the accepted .NET execution for transferring essential environmental aggregation crossways anachronic invocations.&#160; What if we desired to attain it cushy to line culture?&#160; Imagine the mass structure for awaiting a duty with the line of culture:</p>
<blockquote><p>await task.WithCulture();</p>
</blockquote>
<p>We could enable that with cipher same the following:</p>
<blockquote><p>public noise CultureAwaiter WithCurrentCulture(this Task task)        <br />{         <br />&#160;&#160;&#160; convey newborn CultureAwaiter(task);         <br />}</p>
<p>public collection CultureAwaiter        <br />{         <br />&#160;&#160;&#160; clannish readonly TaskAwaiter m_awaiter;         <br />&#160;&#160;&#160; clannish CultureInfo m_culture;</p>
<p>&#160;&#160;&#160; open CultureAwaiter(Task task)        <br />&#160;&#160;&#160; {         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (task == null) intercommunicate newborn ArgumentNullException(&quot;task&quot;);         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_awaiter = task.GetAwaiter();         <br />&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160; open CultureAwaiter GetAwaiter() { convey this; }</p>
<p>&#160;&#160;&#160; open bool BeginAwait(Action continuation)        <br />&#160;&#160;&#160; {         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_culture = Thread.CurrentThread.CurentCulture;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; convey m_awaiter.BeginAwait(continuation);         <br />&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160; open vacuum EndAwait()        <br />&#160;&#160;&#160; {         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Thread.CurrentThread.CurrentCulture = m_culture;         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_awaiter.EndAwait();         <br />&#160;&#160;&#160; }         <br />}</p>
</blockquote>
<p>This awaiter feat wraps a TaskAwaiter, and this implementations BeginAwait and EndAwait methods assign to the contained TaskAwaiter’s.&#160; On crowning of that, though, the feat captures the underway society in BeginAwait and then restores it in EndAwait.</p>
<p>By now, it should be manifest that there are loads of engrossing possibilities here.&#160; I countenance nervy to sight every the engrossing and multipurpose awaiters you become up with.&#160; Just ready in nous that patch there are plentitude of “cool” things you crapper do, cipher understandability and maintainability is rattling important, so attain trusty that the emotionlessness isn’t trumped by demand of clearness most the code’s meaning.</p>
<div></div>
<p><img src="http://blogs.msdn.com/aggbug.aspx?PostID=10115642" width="1" height="1" title="await anything;" alt=" await anything;" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.feedpals.com/await-anything.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>INTERESTED IN WORKING ON TECHNICAL COMPUTING?  WE’RE HIRING!</title>
		<link>http://www.feedpals.com/interested-in-working-on-technical-computing-we%e2%80%99re-hiring.html</link>
		<comments>http://www.feedpals.com/interested-in-working-on-technical-computing-we%e2%80%99re-hiring.html#comments</comments>
		<pubDate>Thu, 13 Jan 2011 16:16:12 +0000</pubDate>
		<dc:creator></dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/shahidsi/public_html/feedpals.com/wp-content/plugins/autometa/autometa.php</b> on line <b>300</b><br />
		<category><![CDATA[.NET Help]]></category>
		<category><![CDATA[plinq]]></category>
		<category><![CDATA[task-parallel-library]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://www.feedpals.com/interested-in-working-on-technical-computing-we%e2%80%99re-hiring.html</guid>
		<description><![CDATA[ The Parallel Computing Platform team is part of a larger organization at Microsoft focused on technical computing , which as Wikipedia describes it “is the application of the mathematical and computational principles of scientific computing to solve practical problems of industrial interest.”&#160; Suffice it to say that there are a ton of interesting problems to be solved in this space.&#160; Want to help do so?&#160; Our organization is hiring, and there are a large variety of interesting positions available.&#160; Want to write code, test code, design systems, or even help run the business?&#160; There’s a job for that.&#160; Want to develop languages, or libraries, or runtimes, or applications?&#160; There’s a job for that, too.&#160; Here are some of the positions currently available: Program Manager Program Manager, Senior Software Development Engineer Software Development Engineer II Software Development Engineer II Software Development Engineer in Test II Software Development Engineer in Test II Software Development Engineer in Test II Software Development Engineer in Test II Software Development Engineer in Test II Software Development Engineer in Test, Senior Software Development Engineer in Test, Senior Business Administrator To apply for one of these positions, go to the relevant page and click the “Apply Now” link. We hope to work with you soon! ]]></description>
			<content:encoded><![CDATA[<p>
<p>The Parallel Computing Platform aggroup is conception of a super methodicalness at Microsoft convergent on <a href="http://www.modelingtheworld.com/">technical computing</a>, which as Wikipedia describes it “is the covering of the mathematical and computational principles of technological technology to cipher applicatory problems of industrialized interest.”&#160; Suffice it to feature that there are a ton of engrossing problems to be resolved in this space.&#160; Want to support do so?&#160; Our methodicalness is hiring, and there are a super difference of engrossing positions available.&#160; </p>
<p>Want to indite code, effort code, organisation systems, or modify support separate the business?&#160; There’s a employ for that.&#160; Want to amend languages, or libraries, or runtimes, or applications?&#160; There’s a employ for that, too.&#160; Here are whatever of the positions currently available:</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Program-Manager-Job-WA-98052/1033920/">Program Manager</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Program-Manager,-Senior-Job-WA-98052/1036371/">Program Manager, Senior</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-Job-WA-98052/1035053/">Software Development Engineer</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-II-Job-WA-98052/1076116/">Software Development Engineer II</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-II-Job-WA-98052/1032531/">Software Development Engineer II</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-in-Test-II-Job-WA-98052/1033175/">Software Development Engineer in Test II</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-in-Test-II-Job-WA-98052/1033928/">Software Development Engineer in Test II</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-in-Test-II-Job-WA-98052/1034143/">Software Development Engineer in Test II</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-in-Test-II-Job-WA-98052/1034720/">Software Development Engineer in Test II</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-in-Test-II-Job-WA-98052/1035593/">Software Development Engineer in Test II</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-in-Test,-Senior-Job-WA-98052/1035090/">Software Development Engineer in Test, Senior</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Software-Development-Engineer-in-Test,-Senior-Job-WA-98052/1033089/">Software Development Engineer in Test, Senior</a></td>
</tr>
<tr>
<td valign="top" width="400"><a href="http://www.microsoft-careers.com/job/Redmond-Business-Administrator-Job-WA-98052/1065606/">Business Administrator</a></td>
</tr>
</tbody>
</table>
<p>To administer for digit of these positions, go to the germane tender and utter the “Apply Now” link.</p>
<p>We wish to impact with you soon!</p>
<div></div>
<p><img src="http://blogs.msdn.com/aggbug.aspx?PostID=10115391" width="1" height="1" title="Interested in working on Technical Computing?  We’re hiring!" alt=" Interested in working on Technical Computing?  We’re hiring!" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.feedpals.com/interested-in-working-on-technical-computing-we%e2%80%99re-hiring.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AWAIT, AND UI, AND DEADLOCKS! OH MY!</title>
		<link>http://www.feedpals.com/await-and-ui-and-deadlocks-oh-my.html</link>
		<comments>http://www.feedpals.com/await-and-ui-and-deadlocks-oh-my.html#comments</comments>
		<pubDate>Thu, 13 Jan 2011 07:13:04 +0000</pubDate>
		<dc:creator></dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/shahidsi/public_html/feedpals.com/wp-content/plugins/autometa/autometa.php</b> on line <b>300</b><br />
		<category><![CDATA[.NET Help]]></category>
		<category><![CDATA[parallelism-blockers]]></category>
		<category><![CDATA[task-parallel-library]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://www.feedpals.com/await-and-ui-and-deadlocks-oh-my.html</guid>
		<description><![CDATA[ It’s been awesome seeing the level of interest developers have had for the Async CTP and how much usage it’s getting.&#160; Of course, with any new technology there are bound to be some hiccups.&#160; One issue I’ve seen arise now multiple times is developers accidentally deadlocking their application by blocking their UI thread, so I thought it would be worthwhile to take a few moments to explore the common cause of this and how to avoid such predicaments. At its core, the new async language functionality aims to restore the ability for developers to write the sequential, imperative code they’re used to writing, but to have it be asynchronous in nature rather than synchronous.&#160; That means that when operations would otherwise tie up the current thread of execution, they’re instead offloaded elsewhere, allowing the current thread to make forward progress and do other useful work while, in effect, asynchronously waiting for the spawned operation to complete.&#160; In both server and client applications, this can be crucial for application scalability, and in client applications in particular it’s also really useful for responsiveness. Most UI frameworks, such as Windows Forms and WPF, utilize a message loop to receive and process incoming messages.&#160; These messages include things like notifications of keys being typed on a keyboard, or buttons being clicked on a mouse, or controls in the user interface being manipulated, or the need to refresh an area of the window, or even the application sending itself a message dictating some code to be executed.&#160; In response to these messages, the UI performs some action, such as redrawing its surface, or changing the text being displayed, or adding items to one of its controls., or running the code that was posted to it.&#160; The “message loop” is typically literally a loop in code, where a thread continually waits for the next message to arrive, processes it, goes back to get the next message, processes it, and so on.&#160; As long as that thread is able to quickly process messages as soon as they arrive, the application remains responsive, and the application’s users remain happy.&#160; If, however, processing a particular message takes too long, the thread running the message loop code will be unable to pick up the next message in a timely fashion, and responsiveness will decrease.&#160; This could take the form of pauses in responding to user input, and if the thread’s delays get bad enough (e.g. an infinite delay), the application “hanging”. In a framework like Windows Forms or WPF, when a user clicks a button, that typically ends up sending a message to the message loop, which translates the message into a call to a handler of some kind, such as a method on the class representing the user interface, e.g.: private void button1_Click(object sender, RoutedEventArgs e) { &#160;&#160;&#160; string s = LoadString(); &#160;&#160;&#160; textBox1.Text = s; } Here, when I click the button1 control, the message will inform WPF to invoke the button1_Click method, which will in turn run a method LoadString to get a string value, and store that string value into the textBox1 control’s Text property.&#160; As long as LoadString is quick to execute, all is well, but the longer LoadString takes, the more time the UI thread is delayed inside button1_Click, unable to return to the message loop to pick up and process the next message. To address that, we can choose to load the string asynchronously, meaning that rather than blocking the thread calling button1_Click from returning to the message loop until the string loading has completed, we’ll instead just have that thread launch the loading operation and then go back to the message loop.&#160; Only when the loading operation completes will we then send another message to the message loop to say “hey, that loading operation you previously started is done, and you can pick up where you left off and continue executing.”&#160; Imagine we had a method: public Task&#60;string&#62; LoadStringAsync(); This method will return very quickly to its caller, handing back a .NET Task&#60;string&#62; object that represents the future completion of the asynchronous operation and its future result.&#160; At some point in the future when the operation completes, the task object will be able to hand out the operations’ result, which could be the string in the case of successful loading, or an exception in the case of failure.&#160; Either way, the task object provides several mechanisms to notify the holder of the object that the loading operation has completed.&#160; One way is to synchronously block waiting for the task to complete, and that can be accomplished by calling the task’s Wait method, or by accessing its Result, which will implicitly wait until the operation has completed… in both of these cases, a call to these members will not complete until the operation has completed.&#160; An alternative way is to receive an asynchronous callback, where you register with the task a delegate that will be invoked when the task completes.&#160; That can be accomplished using one of the Task’s ContinueWith methods.&#160; With ContinueWith, we can now rewrite our previous button1_Click method to not block the UI thread while we’re asynchronously waiting for the loading operation to complete: private void button1_Click(object sender, RoutedEventArgs e) { &#160;&#160;&#160; Task&#60;string&#62; s = LoadStringAsync(); &#160;&#160;&#160; s.ContinueWith(delegate { textBox1.Text = s.Result; }); // warning: buggy } This does in fact asynchronously launch the loading operation, and then asynchronously run the code to store the result into the UI when the operation completes.&#160; However, we now have a new problem.&#160; UI frameworks like Windows Forms, WPF, and Silverlight all place a restriction on which threads are able to access UI controls, namely that the control can only be accessed from the thread that created it.&#160; Here, however, we’re running the callback to update the Text of textBox1on some arbitrary thread, wherever the Task Parallel Library (TPL) implementation of ContinueWith happened to put it.&#160; To address this, we need some way to get back to the UI thread.&#160; Different UI frameworks provide different mechanisms for doing this, but in .NET they all take basically the same shape, a BeginInvoke method you can use to pass some code as a message to the UI thread to be processed: private void button1_Click(object sender, RoutedEventArgs e) { &#160;&#160;&#160; Task&#60;string&#62; s = LoadStringAsync(); &#160;&#160;&#160; s.ContinueWith(delegate &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; Dispatcher.BeginInvoke(new Action(delegate &#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; textBox1.Text = s.Result; &#160;&#160;&#160;&#160;&#160;&#160;&#160; })); &#160;&#160;&#160; }); } The .NET Framework further abstracts over these mechanisms for getting back to the UI thread, and in general a mechanism for posting some code to a particular context, through the SynchronizationContext class.&#160; A framework can establish a current context, available through the SynchronizationContext.Current property, which provides a SynchronizationContext instance representing the current environment.&#160; This instance’s Post method will marshal a delegate back to this environment to be invoked: in a WPF app, that means bringing you back to the dispatcher, or UI thread, you were previously on.&#160; So, we can rewrite the previous code as follows: private void button1_Click(object sender, RoutedEventArgs e) { &#160;&#160;&#160; var sc = SynchronizationContext.Current; &#160;&#160;&#160; Task&#60;string&#62; s = LoadStringAsync(); &#160;&#160;&#160; s.ContinueWith(delegate &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; sc.Post(delegate { textBox1.Text = s.Result; }, null); &#160;&#160;&#160; }); } and in fact this pattern is so common, TPL in .NET 4 provides the TaskScheduler.FromCurrentSynchronizationContext() method, which allows you to do the same thing with code like: private void button1_Click(object sender, RoutedEventArgs e) { &#160;&#160;&#160; LoadStringAsync().ContinueWith(s =&#62; textBox1.Text = s.Result, &#160;&#160;&#160;&#160;&#160;&#160;&#160; TaskScheduler.FromCurrentSynchronizationContext()); } As mentioned, this works by “posting” the delegate back to the UI thread to be executed.&#160; That posting is a message like any other, and it requires the UI thread to go through its message loop, pick up the message, and process it (which will result in invoking the posted delegate).&#160; In order for the delegate to be invoked then, the thread first needs to return to the message loop, which means it must leave the button1_Click method. Now, there’s still a fair amount of boilerplate code to write above, and it gets orders of magnitude worse when you start introducing more complicated flow control constructs, like conditionals and loops.&#160; To address this, the new async language feature allows you to write this same code as: private void button1_Click(object sender, RoutedEventArgs e) { &#160;&#160;&#160; string s = await LoadStringAsync(); &#160;&#160;&#160; textBox1.Text = s; } For all intents and purposes, this is the same as the previous code shown, and you can see how much cleaner it is… in fact, it’s close to identical&#160; in the code required to our original synchronous implementation.&#160; But, of course, this one is asynchronous: after calling LoadStringAsync and getting back the Task&#60;string&#62; object, the remainder of the function is hooked up as a callback that will be posted to the current SynchronizationContext in order to continue execution on the right thread when the loading is complete.&#160; The compiler is layering on some really helpful syntactic sugar here. Now things get interesting. Let’s imagine LoadStringAsync is implemented as follows: static async Task&#60;string&#62; LoadStringAsync() { &#160;&#160;&#160; string firstName = await GetFirstNameAsync(); &#160;&#160;&#160; string lastName = await GetLastNameAsync(); &#160;&#160;&#160; return firstName + &#34; &#34; + lastName; } LoadStringAsync is implemented to first asynchronously retrieve a first name, then asynchronously retrieve a last name, and then return the concatenation of the two.&#160; Notice that it’s using “await”, which, as pointed out previously, is similar to the aforementioned TPL code that uses a continuation to post back to the synchronization context that was current when the await was issued.&#160; So, here’s the crucial point: for LoadStringAsync to complete (i.e. for it to have loaded all of its data and returned its concatenated string, completing the task it returned with that concatenated result), the delegates it posted to the UI thread must have completed.&#160; If the UI thread is unable to get back to the message loop to process messages, it will be unable to pick up the posted delegates that resulted from the asynchronous operations in LoadStringAsync completing, which means the remainder of LoadStringAsync will not run, which means the Task&#60;string&#62; returned from LoadStringAsync will not complete.&#160; It won’t complete until the relevant messages are processed by the message loop. With that in mind, consider this (faulty) reimplementation of button1_Click: private void button1_Click(object sender, RoutedEventArgs e) { &#160;&#160;&#160; Task&#60;string&#62; s = LoadStringAsync(); &#160;&#160;&#160; textBox1.Text = s.Result; // warning: buggy } There’s an exceedingly good chance that this code will hang your application.&#160; The Task&#60;string&#62;.Result property is strongly typed as a String, and thus it can’t return until it has the valid result string to hand back; in other words, it blocks until the result is available.&#160; We’re inside of button1_Click then blocking for LoadStringAsync to complete, but LoadStringAsync’s implementation depends on being able to post code asynchronously back to the UI to be executed, and the task returned from LoadStringAsync won’t complete until it does.&#160; LoadStringAsync is waiting for button1_Click to complete, and button1_Click is waiting for LoadStringAsync to complete. Deadlock! This problem can be exemplified easily without using any of this complicated machinery, e.g.: private void button1_Click(object sender, RoutedEventArgs e) { &#160;&#160;&#160; var mre = new ManualResetEvent(false); &#160;&#160;&#160; SynchronizationContext.Current.Post(_ =&#62; mre.Set(), null); &#160;&#160;&#160; mre.WaitOne(); // warning: buggy } Here, we’re creating a ManualResetEvent, a synchronization primitive that allows us to synchronously wait (block) until the primitive is set.&#160; After creating it, we post back to the UI thread to set the event, and then we wait for it to be set.&#160; But we’re waiting on the very thread that would go back to the message loop to pick up the posted message to do the set operation.&#160; Deadlock. The moral of this (longer than intended) story is that you should not block the UI thread.&#160; Contrary to Nike’s recommendations, just don’t do it.&#160; The new async language functionality makes it easy to asynchronous wait for your work to complete.&#160; So, on your UI thread, instead of writing: Task&#60;string&#62; s = LoadStringAsync(); textBox1.Text = s.Result; // BAD ON UI you can write: Task&#60;string&#62; s = LoadStringAsync(); textBox1.Text = await s; // GOOD ON UI Or instead of writing: Task t = DoWork(); t.Wait(); // BAD ON UI you can write: Task t = DoWork(); await t; // GOOD ON UI This isn’t to say you should never block.&#160; To the contrary, synchronously waiting for a task to complete can be a very effective mechanism, and can exhibit less overhead in many situations than the asynchronous counterpart.&#160; There are also some contexts where asynchronously waiting can be dangerous. For these reasons and others, Task and Task&#60;TResult&#62; support both approaches, so you can have your cake and eat it too.&#160; Just be cognizant of what you’re doing and when, and don’t block your UI thread. (One final note: the Async CTP includes the TaskEx.ConfigureAwait method.&#160; You can use this method to suppress the default behavior of marshaling back to the original synchronization context.&#160; This could have been used, for example, in the LoadStringAsync method to prevent those awaits from needing to return to the UI thread.&#160; This would not only have prevented the deadlock, it would have also resulted in better performance, because we now no longer need to force execution back to the UI thread, when nothing in that method actually needed to run on the UI thread.) ]]></description>
			<content:encoded><![CDATA[<p>
<p>It’s been awing sight the verify of welfare developers hit had for the <a href="http://msdn.com/vstudio/async">Async CTP</a> and how such practice it’s getting.&#160; Of course, with whatever newborn profession there are extremity to be whatever hiccups.&#160; One supply I’ve seen hap today binary nowadays is developers unexpectedly deadlocking their covering by interference their UI thread, so I intellection it would be worthwhile to verify a whatever moments to explore the ordinary drive of this and how to refrain such predicaments.</p>
<p>At its core, the newborn async module functionality aims to change the knowledge for developers to indite the sequential, clamant cipher they’re utilised to writing, but to hit it be anachronic in nature kinda than synchronous.&#160; That effectuation that when dealings would otherwise bond up the underway arrange of execution, they’re instead offloaded elsewhere, allowing the underway arrange to attain nervy advancement and do added multipurpose impact while, in effect, asynchronously inactivity for the spawned activeness to complete.&#160; In both computer and computer applications, this crapper be pivotal for covering scalability, and in computer applications in portion it’s also rattling multipurpose for responsiveness.</p>
<p>Most UI frameworks, such as Windows Forms and WPF, apply a communication wrap to obtain and impact inbound messages.&#160; These messages allow things same notifications of keys existence written on a keyboard, or buttons existence clicked on a mouse, or controls in the individual programme existence manipulated, or the requirement to change an Atlantic of the window, or modify the covering sending itself a communication dictating whatever cipher to be executed.&#160; In salutation to these messages, the UI performs whatever action, such as redrawing its surface, or dynamical the book existence displayed, or adding items to digit of its controls., or streaming the cipher that was posted to it.&#160; The “message loop” is typically literally a wrap in code, where a arrange continually waits for the incoming communication to arrive, processes it, goes backwards to intend the incoming message, processes it, and so on.&#160; As daylong as that arrange is healthy to apace impact messages as presently as they arrive, the covering relic responsive, and the application’s users rest happy.&#160; If, however, processing a portion communication takes likewise long, the arrange streaming the communication wrap cipher module be unable to garner up the incoming communication in a opportune fashion, and sensitiveness module decrease.&#160; This could verify the modify of pauses in responding to individual input, and if the thread’s delays intend intense sufficiency (e.g. an unbounded delay), the covering “hanging”.</p>
<p>In a hold same Windows Forms or WPF, when a individual clicks a button, that typically ends up sending a communication to the communication loop, which translates the communication into a call to a trainer of whatever kind, such as a method on the collection representing the individual interface, e.g.:</p>
<blockquote><p>private vacuum button1_Click(object sender, RoutedEventArgs e)       <br />{        <br />&#160;&#160;&#160; progress s = LoadString();        <br />&#160;&#160;&#160; textBox1.Text = s;        <br />}</p>
</blockquote>
<p>Here, when I utter the button1 control, the communication module inform WPF to advert the button1_Click method, which module in invoke separate a method LoadString to intend a progress value, and accumulation that progress continuance into the textBox1 control’s Text property.&#160; As daylong as LoadString is hurried to execute, every is well, but the individual LoadString takes, the more happening the UI arrange is suspended exclusive button1_Click, unable to convey to the communication wrap to garner up and impact the incoming message.</p>
<p>To come that, we crapper opt to alluviation the progress asynchronously, communication that kinda than interference the arrange occupation button1_Click from backward to the communication wrap until the progress weight has completed, we’ll instead meet hit that arrange move the weight activeness and then go backwards to the communication loop.&#160; Only when the weight activeness completes module we then beam added communication to the communication wrap to feature “hey, that weight activeness you previously started is done, and you crapper garner up where you mitt soured and move executing.”&#160; Imagine we had a method:</p>
<blockquote><p>public Task&lt;string&gt; LoadStringAsync();</p>
</blockquote>
<p>This method module convey rattling apace to its caller, handing backwards a .NET Task&lt;string&gt; goal that represents the forthcoming termination of the anachronic activeness and its forthcoming result.&#160; At whatever saucer in the forthcoming when the activeness completes, the duty goal module be healthy to assistance discover the operations’ result, which could be the progress in the housing of flourishing loading, or an omission in the housing of failure.&#160; Either way, the duty goal provides individual mechanisms to inform the bearer of the goal that the weight activeness has completed.&#160; One artefact is to synchronously country inactivity for the duty to complete, and that crapper be realised by occupation the task’s Wait method, or by accessing its Result, which module implicitly move until the activeness has completed… in both of these cases, a call to these members module not rank until the activeness has completed.&#160; An deciding artefact is to obtain an anachronic callback, where you separate with the duty a assign that module be invoked when the duty completes.&#160; That crapper be realised using digit of the Task’s ContinueWith methods.&#160; With ContinueWith, we crapper today writing our preceding button1_Click method to not country the UI arrange patch we’re asynchronously inactivity for the weight activeness to complete:</p>
<blockquote><p>private vacuum button1_Click(object sender, RoutedEventArgs e)       <br />{        <br />&#160;&#160;&#160; Task&lt;string&gt; s = LoadStringAsync();        <br />&#160;&#160;&#160; s.ContinueWith(delegate { textBox1.Text = s.Result; }); // warning: equipage        <br />}</p>
</blockquote>
<p>This does in fact asynchronously move the weight operation, and then asynchronously separate the cipher to accumulation the termination into the UI when the activeness completes.&#160; However, we today hit a newborn problem.&#160; UI frameworks same Windows Forms, WPF, and Silverlight every locate a regulating on which clothing are healthy to admittance UI controls, videlicet that the curb crapper exclusive be accessed from the arrange that created it.&#160; Here, however, we’re streaming the asking to update the Text of textBox1on whatever capricious thread, wherever the Task Parallel Library (TPL) feat of ContinueWith happened to place it.&#160; To come this, we requirement whatever artefact to intend backwards to the UI thread.&#160; Different UI frameworks wage assorted mechanisms for doing this, but in .NET they every verify essentially the same shape, a BeginInvoke method you crapper ingest to transfer whatever cipher as a communication to the UI arrange to be processed:</p>
<blockquote><p>private vacuum button1_Click(object sender, RoutedEventArgs e)       <br />{        <br />&#160;&#160;&#160; Task&lt;string&gt; s = LoadStringAsync();        <br />&#160;&#160;&#160; s.ContinueWith(delegate        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Dispatcher.BeginInvoke(new Action(delegate        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; textBox1.Text = s.Result;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; }));        <br />&#160;&#160;&#160; });        <br />}</p>
</blockquote>
<p>The .NET Framework boost abstracts over these mechanisms for effort backwards to the UI thread, and in generalized a enforcement for bill whatever cipher to a portion context, finished the SynchronizationContext class.&#160; A hold crapper found a underway context, acquirable finished the SynchronizationContext.Current property, which provides a SynchronizationContext happening representing the underway environment.&#160; This instance’s Post method module lawman a assign backwards to this surround to be invoked: in a WPF app, that effectuation transfer you backwards to the dispatcher, or UI thread, you were previously on.&#160; So, we crapper writing the preceding cipher as follows:</p>
<blockquote><p>private vacuum button1_Click(object sender, RoutedEventArgs e)       <br />{        <br />&#160;&#160;&#160; var sc = SynchronizationContext.Current;        <br />&#160;&#160;&#160; Task&lt;string&gt; s = LoadStringAsync();        <br />&#160;&#160;&#160; s.ContinueWith(delegate        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; sc.Post(delegate { textBox1.Text = s.Result; }, null);        <br />&#160;&#160;&#160; });        <br />}</p>
</blockquote>
<p>and in fact this ornament is so common, TPL in .NET 4 provides the TaskScheduler.FromCurrentSynchronizationContext() method, which allows you to do the same abstract with cipher like:</p>
<blockquote><p>private vacuum button1_Click(object sender, RoutedEventArgs e)       <br />{        <br />&#160;&#160;&#160; LoadStringAsync().ContinueWith(s =&gt; textBox1.Text = s.Result,         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; TaskScheduler.FromCurrentSynchronizationContext());        <br />}</p>
</blockquote>
<p>As mentioned, this entireness by “posting” the assign backwards to the UI arrange to be executed.&#160; That bill is a communication same whatever other, and it requires the UI arrange to go finished its communication loop, garner up the message, and impact it (which module termination in invoking the posted delegate).&#160; In visit for the assign to be invoked then, the arrange prototypal needs to convey to the communication loop, which effectuation it staleness yield the button1_Click method.</p>
<p>Now, there’s ease a clean turn of boilerplate cipher to indite above, and it gets orders of ratio worsened when you move introducing more complicated line curb constructs, same conditionals and loops.&#160; To come this, the newborn async module feature allows you to indite this same cipher as:</p>
<blockquote><p>private vacuum button1_Click(object sender, RoutedEventArgs e)       <br />{        <br />&#160;&#160;&#160; progress s = await LoadStringAsync();        <br />&#160;&#160;&#160; textBox1.Text = s;        <br />}</p>
</blockquote>
<p>For every intents and purposes, this is the same as the preceding cipher shown, and you crapper wager how such preparation it is… in fact, it’s near to identical&#160; in the cipher required to our warning coetaneous implementation.&#160; But, of course, this digit is asynchronous: after occupation LoadStringAsync and effort backwards the Task&lt;string&gt; object, the residual of the duty is crooked up as a asking that module be posted to the underway SynchronizationContext in visit to move enforcement on the correct arrange when the weight is complete.&#160; The programme is layering on whatever rattling adjuvant grammar dulcify here.</p>
<p>Now things intend interesting. Let’s envisage LoadStringAsync is implemented as follows:</p>
<blockquote><p>static async Task&lt;string&gt; LoadStringAsync()       <br />{        <br />&#160;&#160;&#160; progress firstName = await GetFirstNameAsync();        <br />&#160;&#160;&#160; progress lastName = await GetLastNameAsync();        <br />&#160;&#160;&#160; convey firstName + &quot; &quot; + lastName;        <br />}</p>
</blockquote>
<p>LoadStringAsync is implemented to prototypal asynchronously regain a prototypal name, then asynchronously regain a terminal name, and then convey the series of the two.&#160; Notice that it’s using “await”, which, as spinous discover previously, is kindred to the same TPL cipher that uses a postscript to place backwards to the coordination surround that was underway when the await was issued.&#160; So, here’s the pivotal point: for LoadStringAsync to rank (i.e. for it to hit unexploded every of its accumulation and returned its concatenated string, completing the duty it returned with that concatenated result), the delegates it posted to the UI arrange staleness hit completed.&#160; If the UI arrange is unable to intend backwards to the communication wrap to impact messages, it module be unable to garner up the posted delegates that resulted from the anachronic dealings in LoadStringAsync completing, which effectuation the residual of LoadStringAsync module not run, which effectuation the Task&lt;string&gt; returned from LoadStringAsync module not complete.&#160; It won’t rank until the germane messages are computerized by the communication loop.</p>
<p>With that in mind, study this (faulty) reimplementation of button1_Click:</p>
<blockquote><p>private vacuum button1_Click(object sender, RoutedEventArgs e)       <br />{        <br />&#160;&#160;&#160; Task&lt;string&gt; s = LoadStringAsync();        <br />&#160;&#160;&#160; textBox1.Text = s.Result; // warning: equipage        <br />}</p>
</blockquote>
<p>There’s an extremely beatific quantity that this cipher module secure your application.&#160; The Task&lt;string&gt;.Result concept is strongly written as a String, and thusly it can’t convey until it has the legal termination progress to assistance back; in added words, it blocks until the termination is available.&#160; We’re exclusive of button1_Click then interference for LoadStringAsync to complete, but LoadStringAsync’s feat depends on existence healthy to place cipher asynchronously backwards to the UI to be executed, and the duty returned from LoadStringAsync won’t rank until it does.&#160; LoadStringAsync is inactivity for button1_Click to complete, and button1_Click is inactivity for LoadStringAsync to complete. Deadlock!</p>
<p>This difficulty crapper be exemplified easily without using whatever of this complicated machinery, e.g.:</p>
<blockquote><pre>private vacuum button1_Click(object sender, RoutedEventArgs e){&#160;&#160;&#160; var mre = newborn ManualResetEvent(false);&#160;&#160;&#160; SynchronizationContext.Current.Post(_ =&gt; mre.Set(), null);&#160;&#160;&#160; mre.WaitOne(); // warning: buggy}</pre>
</blockquote>
<p>Here, we’re creating a ManualResetEvent, a coordination fraudulence that allows us to synchronously move (block) until the fraudulence is set.&#160; After creating it, we place backwards to the UI arrange to ordered the event, and then we move for it to be set.&#160; But we’re inactivity on the rattling arrange that would go backwards to the communication wrap to garner up the posted communication to do the ordered operation.&#160; Deadlock.</p>
<p>The moralistic of this (longer than intended) news is that you should not country the UI thread.&#160; Contrary to Nike’s recommendations, meet <em>don’t</em> do it.&#160; The newborn async module functionality makes it cushy to anachronic move for your impact to complete.&#160; So, on your UI thread, instead of writing:</p>
<blockquote>
<p>Task&lt;string&gt; s = LoadStringAsync();<br />
      <br />textBox1.Text = s.Result; // BAD ON UI</p>
</blockquote>
<p>you crapper write:</p>
<blockquote>
<p>Task&lt;string&gt; s = LoadStringAsync();<br />
      <br />textBox1.Text = await s; // GOOD ON UI</p>
</blockquote>
<p>Or instead of writing:</p>
<blockquote>
<p>Task t = DoWork();<br />
      <br />t.Wait(); // BAD ON UI</p>
</blockquote>
<p>you crapper write:</p>
<blockquote>
<p>Task t = DoWork();<br />
      <br />await t; // GOOD ON UI</p>
</blockquote>
<p>This isn’t to feature you should never block.&#160; To the contrary, synchronously inactivity for a duty to rank crapper be a rattling trenchant mechanism, and crapper show inferior disbursement in whatever situations than the anachronic counterpart.&#160; There are also whatever contexts where asynchronously inactivity crapper be dangerous. For these reasons and others, Task and Task&lt;TResult&gt; hold both approaches, so you crapper hit your country and take it too.&#160; Just be cognizant of what you’re doing and when, and don’t country your UI thread.</p>
<p>(One test note: the Async CTP includes the TaskEx.ConfigureAwait method.&#160; You crapper ingest this method to bury the choice activity of marshaling backwards to the warning coordination context.&#160; This could hit been used, for example, in the LoadStringAsync method to preclude those awaits from needing to convey to the UI thread.&#160; This would not exclusive hit prevented the deadlock, it would hit also resulted in meliorate performance, because we today no individual requirement to obligate enforcement backwards to the UI thread, when null in that method actually necessary to separate on the UI thread.)</p>
<div></div>
<p><img src="http://blogs.msdn.com/aggbug.aspx?PostID=10115163" width="1" height="1" title="Await, and UI, and deadlocks! Oh my!" alt=" Await, and UI, and deadlocks! Oh my!" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.feedpals.com/await-and-ui-and-deadlocks-oh-my.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PROCESSING SEQUENCES OF ASYNCHRONOUS OPERATIONS WITH TASKS</title>
		<link>http://www.feedpals.com/processing-sequences-of-asynchronous-operations-with-tasks.html</link>
		<comments>http://www.feedpals.com/processing-sequences-of-asynchronous-operations-with-tasks.html#comments</comments>
		<pubDate>Mon, 22 Nov 2010 06:13:38 +0000</pubDate>
		<dc:creator></dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/shahidsi/public_html/feedpals.com/wp-content/plugins/autometa/autometa.php</b> on line <b>300</b><br />
		<category><![CDATA[.NET Help]]></category>
		<category><![CDATA[-net-4]]></category>
		<category><![CDATA[parallelextensionsextras]]></category>
		<category><![CDATA[task-parallel-library]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://www.feedpals.com/processing-sequences-of-asynchronous-operations-with-tasks.html</guid>
		<description><![CDATA[ Of late, I’ve seen multiple folks asking about how to use tasks to asynchronously execute a sequence of operations.&#160; For example, given three synchronous functions: public string DoA(string input); public string DoB(string aResult); public string DoC(string bResult); you could invoke these functions with code like: string aResult = DoA(input); string bResult = DoB(aResult); string cResult = DoC(bResult); Then, given Task-based asynchronous counterparts to these functions: public static Task&#60;string&#62; DoAAsync(string input); public static Task&#60;string&#62; DoBAsync(string aResult); public static Task&#60;string&#62; DoCAsync(string bResult); how would you asynchronously do the equivalent of the synchronous code previously shown? Async CTP and Language Support The Async CTP highlights a great way to handle this once C# and Visual Basic have built-in support for awaiting tasks.&#160; With that language support, the asynchronous version looks almost identical to the synchronous, albeit with a few extra keywords thrown in: string aResult = await DoAAsync(input); string bResult = await DoBAsync(aResult); string cResult = await DoCAsync(bResult); Lovely! Of course, .NET 4 doesn’t currently support that special syntax out-of-the-box, so what can we do in the meantime?&#160; It’s important to realize that the Async CTP just builds on top of what’s available in .NET 4, so while the compiler here is doing what compilers do best and writing lots of boilerplate so that you don’t have to, the generated code is really still just using existing support in the Task Parallel Library.&#160; We can use that support directly, too. ContinueWith and Unwrap One approach is to just use what’s provided in TPL without utilizing any additional helpers.&#160; The Task.ContinueWith method schedules code to run when the antecedent task completes, and returns a Task (or Task&#60;TResult&#62;) to represent that subsequent operation.&#160; So, we can try to handle the first chained call with code like the following: var aResult = DoAAsync(input); var bResult = aResult.ContinueWith(t =&#62; DoBAsync(t.Result)); This isn’t quite right, however.&#160; This overload of ContinueWith creates a Task&#60;TResult&#62;, but the TResult here will be typed as the result of DoBAsync, which is Task&#60;string&#62;.&#160; Thus, the instance returned from the ContinueWith call will be a Task&#60;Task&#60;string&#62;&#62;, which is not what we want.&#160; To handle those nested tasks, we can utilize the Unwrap method included in TPL to “unwrap” the inner nested task, converting the Task&#60;Task&#60;string&#62;&#62; into the Task&#60;string&#62; we desire.&#160; And with that small change, we can now complete our example: var aResult = DoAAsync(input); var bResult = aResult.ContinueWith(t =&#62; DoBAsync(t.Result)).Unwrap(); var cResult = bResult.ContinueWith(t =&#62; DoCAsync(t.Result)).Unwrap(); This approach works, and it may be all you need, but it does have a couple of downsides.&#160; First, what happens if DoAAsync fails such that the returned task is faulted rather than running to completion?&#160; In that case, the continuation off of aResult will still execute, and accessing the t.Result inside that function will propagate the exception.&#160; That will cause bResult to be faulted, and its continuation will fire, with that continuation’s t.Result propagating the exception, and so on.&#160; Net net, cResult will appropriately be faulted, but more work will have happened than was necessary (e.g. we invoked the continuations for B and C when we didn’t have to, and we threw several more exceptions than we needed to), and each time the exception was propagated it was wrapped in another level of AggregateException, so cResult will contain an AggregateException containing an AggregateException containing… and so on (AggregateException’s Flatten method is great for reducing these extra levels of aggregation, by the way).&#160; Second, it’s a bit more code than you may otherwise like to write.&#160; Can we do better? Then One of the really nice things about Tasks is that they enable good composition.&#160; Once you have a single type capable of representing any arbitrary asynchronous operation, you can write “combinators” over the type that allow you to combine/compose asynchronous operations in a myriad of ways.&#160; For example, we can abstract away this sequential combination notion into a Then combinator, and at the same time take care of the previously mentioned exception handling concerns. Our goal here will be to build the following operator: public static Task&#60;T2&#62; Then&#60;T1, T2&#62;(this Task&#60;T1&#62; first, Func&#60;T1, Task&#60;T2&#62;&#62; next); With that in place, we can then use it to re-implement our desired functionality with code like: var aResult = DoAAsync(input); var bResult = aResult.Then(s =&#62; DoBAsync(s)); var cResult = bResult.Then(s =&#62; DoCAsync(s)); The behavior of “Then” is that when the first task completes, the next function is invoked to produce a task and is provided with the output from the previous task.&#160; The task returned from Then primarily represents the task returned by the next function’s invocation; however, if the first task is canceled or faults, the next function will not be invoked, and the returned task will instead represent the first task.&#160; With this approach, we can chain Then calls together as was done in the above example, and the final task produced from the chain will represent all of the processing. To implement Then, we first need the scaffolding to do argument validation and to create the task that Then will return: public static Task&#60;T2&#62; Then&#60;T1, T2&#62;(this Task&#60;T1&#62; first, Func&#60;T1, Task&#60;T2&#62;&#62; next) { &#160;&#160;&#160; if (first == null) throw new ArgumentNullException(&#34;first&#34;); &#160;&#160;&#160; if (next == null) throw new ArgumentNullException(&#34;next&#34;); &#160;&#160;&#160; var tcs = new TaskCompletionSource&#60;T2&#62;(); &#160;&#160;&#160; … // TODO #1: implement Then logic &#160;&#160;&#160; return tcs.Task; } This code validates that the source task and the function to produce the subsequent task are both non-null.&#160; It then creates a TaskCompletionSource&#60;TResult&#62; which is used to return a Task from Then; the rest of our implementation will be all about completing that TCS task with the appropriate state.&#160; Now we just need to fill in that TODO #1: // in place of TODO #1 above first.ContinueWith(delegate { &#160;&#160;&#160; if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions);&#160; &#160;&#160;&#160; else if (first.IsCanceled) tcs.TrySetCanceled(); &#160;&#160;&#160; else &#160;&#160;&#160; { &#160; &#160;&#160;&#160;&#160;&#160;&#160; … // TODO #2: handle successful completion of first &#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously); } We’re utilizing a continuation off of the first task to run some code when the task completes.&#160; If it completes due to faulting, we transfer its exceptions to the TCS task we’re returning from Then, and we’re done.&#160; Similarly, if the first task was canceled, we cancel the TCS task.&#160; That just leaves a RanToCompletion final state, meaning that the first task completed successfully, and we’ll handle that case in a moment.&#160; The other thing to notice is that we’ve specified that this continuation task should ExecuteSynchronously: that just means that, if possible, this continuation function will run synchronously with regards to the first task completing, ideally happening on the same thread immediately after first completes, rather than TPL scheduling the task to execute later.&#160; Now let’s complete our implementation by finishing TODO #2: // in place of TODO #2 above try { &#160;&#160;&#160; var t = next(first.Result); &#160;&#160;&#160; if (t == null) tcs.TrySetCanceled(); &#160;&#160;&#160; else t.ContinueWith(delegate &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions); &#160;&#160;&#160;&#160;&#160;&#160;&#160; else if (t.IsCanceled) tcs.TrySetCanceled(); &#160;&#160;&#160;&#160;&#160;&#160;&#160; else tcs.TrySetResult(t.Result); &#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously); } catch (Exception exc) { tcs.TrySetException(exc); } Here we invoke the next function with the result of the first task.&#160; If for some reason next returns null, we’ve opted to cancel the TCS task, but this could be changed to fault it or to do something else entirely, based on your desired semantics.&#160; Assuming a non-null Task is returned, we then continue from that task.&#160; This is done to enable transferring of the results from the that task to the TCS task since, as mentioned, the TCS task returned from Then should be a proxy for this inner task object.&#160; The rest should look familiar, simply transferring the final state and associated data from this inner task to the TCS task.&#160; Here’s our final implementation of this method: public static Task&#60;T2&#62; Then&#60;T1, T2&#62;(this Task&#60;T1&#62; first, Func&#60;T1, Task&#60;T2&#62;&#62; next) { &#160;&#160;&#160; if (first == null) throw new ArgumentNullException(&#34;first&#34;); &#160;&#160;&#160; if (next == null) throw new ArgumentNullException(&#34;next&#34;); &#160;&#160;&#160; var tcs = new TaskCompletionSource&#60;T2&#62;(); &#160;&#160;&#160; first.ContinueWith(delegate &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions); &#160;&#160;&#160;&#160;&#160;&#160;&#160; else if (first.IsCanceled) tcs.TrySetCanceled(); &#160;&#160;&#160;&#160;&#160;&#160;&#160; else &#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; try &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var t = next(first.Result); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (t == null) tcs.TrySetCanceled(); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else t.ContinueWith(delegate &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else if (t.IsCanceled) tcs.TrySetCanceled(); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else tcs.TrySetResult(t.Result); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; } &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; catch (Exception exc) { tcs.TrySetException(exc); } &#160;&#160;&#160;&#160;&#160;&#160;&#160; } &#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously); &#160;&#160;&#160; return tcs.Task; } There are of course many variations on this possible, and you could imagine building up several overloads of Then to handle a multitude of cases for creating chains of asynchronous processing, e.g. public static Task Then(this Task first, Action next); public static Task Then(this Task first, Func&#60;Task&#62; next); public static Task&#60;T2&#62; Then&#60;T2&#62;(this Task first, Func&#60;T2&#62; next); public static Task&#60;T2&#62; Then&#60;T2&#62;(this Task first, Func&#60;Task&#60;T2&#62;&#62; next); public static Task Then&#60;T1&#62;(this Task&#60;T1&#62; first, Action&#60;T1&#62; next); public static Task Then&#60;T1&#62;(this Task&#60;T1&#62; first, Func&#60;T1,Task&#62; next); public static Task&#60;T2&#62; Then&#60;T1,T2&#62;(this Task&#60;T1&#62; first, Func&#60;T1,T2&#62; next); public static Task&#60;T2&#62; Then&#60;T1,T2&#62;(this Task&#60;T1&#62; first, Func&#60;T1, Task&#60;T2&#62;&#62; next); Sequence With such methods, we can create additional abstractions for sequential processing as well.&#160; Let’s say we did have an implementation for an additional one of the above overloads: public static Task Then(this Task first, Func&#60;Task&#62; next) { &#160;&#160;&#160; if (first == null) throw new ArgumentNullException(&#34;first&#34;); &#160;&#160;&#160; if (next == null) throw new ArgumentNullException(&#34;next&#34;); &#160;&#160;&#160; var tcs = new TaskCompletionSource&#60;object&#62;(); &#160;&#160;&#160; first.ContinueWith(delegate &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions); &#160;&#160;&#160;&#160;&#160;&#160;&#160; else if (first.IsCanceled) tcs.TrySetCanceled(); &#160;&#160;&#160;&#160;&#160;&#160;&#160; else &#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; try &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var t = next(); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (t == null) tcs.TrySetCanceled(); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else t.ContinueWith(delegate &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else if (t.IsCanceled) tcs.TrySetCanceled(); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else tcs.TrySetResult(null); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; } &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; catch (Exception exc) { tcs.TrySetException(exc); } &#160;&#160;&#160;&#160;&#160;&#160;&#160; } &#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously); &#160;&#160;&#160; return tcs.Task; } We can layer a Sequence method on top of this as follows: public static Task Sequence(params Func&#60;Task&#62; [] actions) { &#160;&#160;&#160; Task last = null; &#160;&#160;&#160; foreach (var action in actions) &#160;&#160;&#160; { last = (last == null) ? Task.Factory.StartNew(action).Unwrap() : last.Then(action); &#160;&#160;&#160; } &#160;&#160;&#160; return last; } and with such a Sequence method, we’re now able to write a set of lambdas that will be processed asynchronously one after the other, e.g. Task&#60;string&#62; aResult = null, bResult = null, cResult = null; Sequence( &#160;&#160;&#160; () =&#62; { return aResult = DoAAsync(input); }, &#160;&#160;&#160; () =&#62; { return bResult = DoBAsync(aResult.Result); }, &#160;&#160;&#160; () =&#62; { return cResult = DoCAsync(bResult.Result); }); Iterate We can build other interesting combinators for sequential processing, including one that takes advantage of C# iterators.&#160; There are several popular frameworks that use C# iterators to drive asynchronous processing, and the same trick employed in those can be used with tasks.&#160; Here’s a basic example of such a driver: public static Task Iterate(IEnumerable&#60;Task&#62; asyncIterator) { &#160;&#160;&#160; if (asyncIterator == null) throw new ArgumentNullException(&#34;asyncIterator&#34;); &#160;&#160;&#160; var enumerator = asyncIterator.GetEnumerator(); &#160;&#160;&#160; if (enumerator == null) throw new InvalidOperationException(&#34;Invalid enumerable - GetEnumerator returned null&#34;); &#160;&#160;&#160; var tcs = new TaskCompletionSource&#60;object&#62;(); &#160;&#160;&#160; tcs.Task.ContinueWith(_ =&#62; enumerator.Dispose(), TaskContinuationOptions.ExecuteSynchronously); &#160;&#160;&#160; Action&#60;Task&#62; recursiveBody = null; &#160;&#160;&#160; recursiveBody = delegate { &#160;&#160;&#160;&#160;&#160;&#160;&#160; try { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (enumerator.MoveNext()) enumerator.Current.ContinueWith(recursiveBody, TaskContinuationOptions.ExecuteSynchronously); &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else tcs.TrySetResult(null); &#160;&#160;&#160;&#160;&#160;&#160;&#160; } &#160;&#160;&#160;&#160;&#160;&#160;&#160; catch (Exception exc) { tcs.TrySetException(exc); } &#160;&#160;&#160; }; &#160;&#160;&#160; recursiveBody(null); &#160;&#160;&#160; return tcs.Task; } This Iterate method accepts an enumerable of tasks.&#160; This enumerable needs to be lazy, such that the next task isn’t generated until MoveNext is called to retrieve it; this is exactly the behavior we’ll generally get with a C# iterator (and a VB iterator in Async CTP, but if you have the Async CTP, you should just use await as called out at the beginning of this post).&#160; The Iterate method retrieves an enumerator and begins by calling MoveNext on it.&#160; The task returned from the enumerator as Current then has a continuation hooked up to it which, when the retrieved task completes, starts that process again, calling MoveNext on the enumerator, hooking up a continuation, and so on.&#160; Only once MoveNext throws an exception or returns false does this process end.&#160; With such an Iterate method in place, we can now rewrite our original sample with a method like this: IEnumerable&#60;Task&#62; DoExample(string input) { &#160;&#160;&#160; var aResult = DoAAsync(input); &#160;&#160;&#160; yield return aResult; &#160;&#160;&#160; var bResult = DoBAsync(aResult.Result); &#160;&#160;&#160; yield return bResult; &#160;&#160;&#160; var cResult = DoCAsync(bResult.Result); &#160;&#160;&#160; yield return cResult; &#160;&#160;&#160; … } which we then invoke with code like: Task t = Iterate(DoExample(“42”)); There are of course many variations on the Iterate implementation you could easily add.&#160; For example, you might want the iteration to stop if a retrieved task ends in the faulted state; that can be accomplished with some minor modifications to the recursiveBody function. LINQ Getting slightly more wacky (but still within the realm of reasonable), we can utilize the C# and VB LINQ syntax to also express sequential processing.&#160; The C# and VB compilers are pattern-based in their support of the .NET standard query operators, allowing you to use from, select, and so on with arbitrary data types as long as methods matching the right signature are exposed.&#160; We can, for example, implement an appropriate SelectMany operator as an extensions method on top of Task&#60;TResult&#62;: static class Extensions { &#160;&#160;&#160; public static Task&#60;TResult&#62; SelectMany&#60;TSource, TCollection, TResult&#62;( &#160;&#160;&#160;&#160;&#160;&#160;&#160; this Task&#60;TSource&#62; source, &#160;&#160;&#160;&#160;&#160;&#160;&#160; Func&#60;TSource, Task&#60;TCollection&#62;&#62; collectionSelector, &#160;&#160;&#160;&#160;&#160;&#160;&#160; Func&#60;TSource, TCollection, TResult&#62; resultSelector) &#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160; if (source == null) throw new ArgumentNullException(&#34;source&#34;); &#160;&#160;&#160;&#160;&#160;&#160;&#160; if (collectionSelector == null) throw new ArgumentNullException(&#34;collectionSelector&#34;); &#160;&#160;&#160;&#160;&#160;&#160;&#160; if (resultSelector == null) throw new ArgumentNullException(&#34;resultSelector&#34;); &#160;&#160;&#160;&#160;&#160;&#160;&#160; return source.ContinueWith(t =&#62; &#160;&#160;&#160;&#160;&#160;&#160;&#160; { &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return collectionSelector(t.Result). &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ContinueWith(c =&#62; resultSelector(t.Result, c.Result), TaskContinuationOptions.NotOnCanceled); &#160;&#160;&#160;&#160;&#160;&#160;&#160; }, TaskContinuationOptions.NotOnCanceled).Unwrap(); &#160;&#160;&#160; } } and with that, we can then re-implement our original example with code like: var result = from aResult in DoAAsync(&#34;42&#34;) &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; from bResult in DoBAsync(aResult) &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; from cResult in DoCAsync(bResult) &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; select cResult; An implementation of a bunch of the LINQ operators targeting tasks is available as part of the Parallel Extensions Extras project at http://code.msdn.microsoft.com/ParExtSamples .&#160; If instead we were to utilize the Reactive Extensions available for download from the DevLabs site, we can utilize the ToObservable extension method it provides for Task&#60;TResult&#62;, and then utilize Rx’s robust LINQ implementation to do the same thing, e.g. var result = from aResult in DoAAsync(&#34;42&#34;).ToObservable() &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; from bResult in DoBAsync(aResult).ToObservable() &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; from cResult in DoCAsync(bResult).ToObservable() &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; select cResult; F# Async Workflows Out-of-the-box in Visual Studio 2010, F# supports asynchronous workflows and has built-in capability for awaiting tasks.&#160; This allows you to write the original example with code like: let example = async { &#160;&#160;&#160; let! aResult = Async.AwaitTask DoAAsync() &#160;&#160;&#160; let! bResult = Async.AwaitTask DoBAsync() &#160;&#160;&#160; let! cResult = Async.AwaitTask DoCAsync() &#160;&#160;&#160; … } Summary As you can see, there are many useful and interesting ways to achieve sequential, asynchronous processing using Tasks.&#160; Eventually when built-in language support is available for awaiting tasks, that will be the easiest and the recommended approach for developing asynchronous code of this nature.&#160; In the meantime, you can try out such support in the Async CTP , and you can use other techniques as described in this blog post to achieve similar kinds of processing today, assured that you’ll be able to update that code in the future with the more powerful language capabilities when they’re available. Happy coding! ]]></description>
			<content:encoded><![CDATA[<p>
<p>Of late, I’ve seen binary folks asking most how to ingest tasks to asynchronously fulfil a ordering of operations.&#160; For example, presented threesome coetaneous functions:</p>
<blockquote><p>public progress DoA(string input);       <br />public progress DoB(string aResult);        <br />public progress DoC(string bResult);</p>
</blockquote>
<p>you could advert these functions with cipher like:</p>
<blockquote><p>string aResult = DoA(input);       <br />string bResult = DoB(aResult);        <br />string cResult = DoC(bResult);</p>
</blockquote>
<p>Then, presented Task-based anachronic counterparts to these functions:</p>
<blockquote><p>public noise Task&lt;string&gt; DoAAsync(string input);       <br />public noise Task&lt;string&gt; DoBAsync(string aResult);        <br />public noise Task&lt;string&gt; DoCAsync(string bResult);</p>
</blockquote>
<p>how would you asynchronously do the equal of the coetaneous cipher previously shown?</p>
<p><strong>Async CTP and Language Support</strong></p>
<p>The <a href="http://msdn.com/vstudio/async">Async CTP</a> highlights a enthusiastic artefact to appendage this erst C# and Visual Basic hit built-in hold for awaiting tasks.&#160; With that module support, the anachronic edition looks nearly aforementioned to the synchronous, albeit with a whatever player keywords tangled in:</p>
<blockquote><p>string aResult = await DoAAsync(input);       <br />string bResult = await DoBAsync(aResult);        <br />string cResult = await DoCAsync(bResult);</p>
</blockquote>
<p>Lovely! Of course, .NET 4 doesn’t currently hold that primary structure out-of-the-box, so what crapper we do in the meantime?&#160; It’s essential to actualise that the Async CTP meet builds on crowning of what’s acquirable in .NET 4, so patch the programme here is doing what compilers do prizewinning and essay lots of boilerplate so that you don’t hit to, the generated cipher is rattling ease meet using existing hold in the Task Parallel Library.&#160; We crapper ingest that hold directly, too.</p>
<p><strong>ContinueWith and Unwrap</strong></p>
<p>One move is to meet ingest what’s provided in TPL without utilizing whatever added helpers.&#160; The Task.ContinueWith method schedules cipher to separate when the prior duty completes, and returns a Task (or Task&lt;TResult&gt;) to equal that ensuant operation.&#160; So, we crapper essay to appendage the prototypal bound call with cipher aforementioned the following:</p>
<blockquote><p>var aResult = DoAAsync(input);       <br />var bResult = aResult.ContinueWith(t =&gt; DoBAsync(t.Result));</p>
</blockquote>
<p>This isn’t quite right, however.&#160; This burden of ContinueWith creates a Task&lt;TResult&gt;, but the TResult here module be written as the termination of DoBAsync, which is Task&lt;string&gt;.&#160; Thus, the event returned from the ContinueWith call module be a Task&lt;Task&lt;string&gt;&gt;, which is not what we want.&#160; To appendage those nested tasks, we crapper apply the Unwrap method included in TPL to “unwrap” the intrinsic nested task, converting the Task&lt;Task&lt;string&gt;&gt; into the Task&lt;string&gt; we desire.&#160; And with that diminutive change, we crapper today rank our example:</p>
<blockquote><p>var aResult = DoAAsync(input);       <br />var bResult = aResult.ContinueWith(t =&gt; DoBAsync(t.Result)).Unwrap();        <br />var cResult = bResult.ContinueWith(t =&gt; DoCAsync(t.Result)).Unwrap();</p>
</blockquote>
<p>This move works, and it haw be every you need, but it does hit a pair of downsides.&#160; First, what happens if DoAAsync fails much that the returned duty is faulted kinda than streaming to completion?&#160; In that case, the postscript soured of aResult module ease execute, and accessing the t.Result exclusive that duty module move the exception.&#160; That module intend bResult to be faulted, and its postscript module fire, with that continuation’s t.Result propagating the exception, and so on.&#160; Net net, cResult module befittingly be faulted, but more impact module hit happened than was necessary (e.g. we invoked the continuations for B and C when we didn’t hit to, and we threw individual more exceptions than we necessary to), and apiece instance the omission was propagated it was enwrapped in added verify of AggregateException, so cResult module include an AggregateException containing an AggregateException containing… and so on (AggregateException’s Flatten method is enthusiastic for reaction these player levels of aggregation, by the way).&#160; Second, it’s a taste more cipher than you haw otherwise aforementioned to write.&#160; Can we do better?</p>
<p><strong>Then</strong></p>
<p>One of the rattling pleasant things most Tasks is that they enable beatific composition.&#160; Once you hit a azygos identify confident of representing whatever capricious anachronic operation, you crapper indite “combinators” over the identify that earmark you to combine/compose anachronic dealings in a myriad of ways.&#160; For example, we crapper nonfigurative absent this sequential compounding idea into a Then combinator, and at the aforementioned instance verify tending of the previously mentioned omission direction concerns. Our content here module be to physique the mass operator:</p>
<blockquote><p>public noise Task&lt;T2&gt; Then&lt;T1, T2&gt;(this Task&lt;T1&gt; first, Func&lt;T1, Task&lt;T2&gt;&gt; next);</p>
</blockquote>
<p>With that in place, we crapper then ingest it to re-implement our desirable functionality with cipher like:</p>
<blockquote><p>var aResult = DoAAsync(input);       <br />var bResult = aResult.Then(s =&gt; DoBAsync(s));        <br />var cResult = bResult.Then(s =&gt; DoCAsync(s));</p>
</blockquote>
<p>The activity of “Then” is that when the <em>first</em> duty completes, the <em>next</em> duty is invoked to display a duty and is provided with the production from the preceding task.&#160; The duty returned from Then primarily represents the duty returned by the <em>next</em> function’s invocation; however, if the <em>first</em> duty is canceled or faults, the <em>next</em> duty module not be invoked, and the returned duty module instead equal the <em>first</em> task.&#160; With this approach, we crapper concern Then calls unitedly as was finished in the above example, and the test duty produced from the concern module equal every of the processing.</p>
<p>To compel Then, we prototypal requirement the system to do discussion determination and to create the duty that Then module return:</p>
<blockquote><p>public noise Task&lt;T2&gt; Then&lt;T1, T2&gt;(this Task&lt;T1&gt; first, Func&lt;T1, Task&lt;T2&gt;&gt; next)       <br />{        <br />&#160;&#160;&#160; if (first == null) intercommunicate newborn ArgumentNullException(&quot;first&quot;);        <br />&#160;&#160;&#160; if (next == null) intercommunicate newborn ArgumentNullException(&quot;next&quot;);</p>
<p>&#160;&#160;&#160; var tcs = newborn TaskCompletionSource&lt;T2&gt;();       <br />&#160;&#160;&#160; <strong>… // TODO #1: compel Then system         <br /></strong>&#160;&#160;&#160; convey tcs.Task;        <br />}</p>
</blockquote>
<p>This cipher validates that the maker duty and the duty to display the ensuant duty are both non-null.&#160; It then creates a TaskCompletionSource&lt;TResult&gt; which is utilised to convey a Task from Then; the rest of our feat module be every most completing that TCS duty with the pertinent state.&#160; Now we meet requirement to modify in that TODO #1:</p>
<blockquote><p>// in locate of TODO #1 above       <br />first.ContinueWith(delegate        <br />{        <br />&#160;&#160;&#160; if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions);&#160; <br />&#160;&#160;&#160; added if (first.IsCanceled) tcs.TrySetCanceled();        <br />&#160;&#160;&#160; added        <br />&#160;&#160;&#160; {        <br />&#160;<strong>&#160;&#160;&#160;&#160;&#160;&#160; … // TODO #2: appendage flourishing termination of prototypal         <br /></strong>&#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously);        <br />}</p>
</blockquote>
<p>We’re utilizing a postscript soured of the <em>first</em> duty to separate whatever cipher when the duty completes.&#160; If it completes cod to faulting, we designate its exceptions to the TCS duty we’re backward from Then, and we’re done.&#160; Similarly, if the <em>first</em> duty was canceled, we equilibrate the TCS task.&#160; That meet leaves a RanToCompletion test state, message that the <em>first</em> duty rank successfully, and we’ll appendage that housing in a moment.&#160; The another abstract to attending is that we’ve given that this postscript duty should ExecuteSynchronously: that meet effectuation that, if possible, this postscript duty module separate synchronously with regards to the prototypal duty completing, ideally event on the aforementioned arrange directly after <em>first</em> completes, kinda than TPL planning the duty to fulfil later.&#160; Now let’s rank our feat by closing TODO #2:</p>
<blockquote><p>// in locate of TODO #2 above       <br />try        <br />{        <br />&#160;&#160;&#160; var t = next(first.Result);        <br />&#160;&#160;&#160; if (t == null) tcs.TrySetCanceled();        <br />&#160;&#160;&#160; added t.ContinueWith(delegate        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; added if (t.IsCanceled) tcs.TrySetCanceled();        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; added tcs.TrySetResult(t.Result);        <br />&#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously);        <br />}        <br />catch (Exception exc) { tcs.TrySetException(exc); }</p>
</blockquote>
<p>Here we advert the <em>next</em> duty with the termination of the <em>first</em> task.&#160; If for whatever think <em>next</em> returns null, we’ve opted to equilibrate the TCS task, but this could be denaturized to imperfectness it or to do something added entirely, supported on your desirable semantics.&#160; Assuming a non-null Task is returned, we then move from that task.&#160; This is finished to enable transferring of the results from the that duty to the TCS duty since, as mentioned, the TCS duty returned from Then should be a agent for this intrinsic duty object.&#160; The rest should countenance familiar, only transferring the test land and related accumulation from this intrinsic duty to the TCS task.&#160; Here’s our test feat of this method:</p>
<blockquote><p>public noise Task&lt;T2&gt; Then&lt;T1, T2&gt;(this Task&lt;T1&gt; first, Func&lt;T1, Task&lt;T2&gt;&gt; next)       <br />{        <br />&#160;&#160;&#160; if (first == null) intercommunicate newborn ArgumentNullException(&quot;first&quot;);        <br />&#160;&#160;&#160; if (next == null) intercommunicate newborn ArgumentNullException(&quot;next&quot;);</p>
<p>&#160;&#160;&#160; var tcs = newborn TaskCompletionSource&lt;T2&gt;();       <br />&#160;&#160;&#160; first.ContinueWith(delegate        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; added if (first.IsCanceled) tcs.TrySetCanceled();        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; added        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; essay        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var t = next(first.Result);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (t == null) tcs.TrySetCanceled();        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; added t.ContinueWith(delegate        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; added if (t.IsCanceled) tcs.TrySetCanceled();        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; added tcs.TrySetResult(t.Result);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; grownup (Exception exc) { tcs.TrySetException(exc); }        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; }        <br />&#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously);        <br />&#160;&#160;&#160; convey tcs.Task;        <br />}</p>
</blockquote>
<p>There are of instruction whatever variations on this possible, and you could envisage antiquity up individual overloads of Then to appendage a assemblage of cases for creating chains of anachronic processing, e.g.</p>
<blockquote><p>public noise Task Then(this Task first, Action next);       <br />public noise Task Then(this Task first, Func&lt;Task&gt; next);        <br />public noise Task&lt;T2&gt; Then&lt;T2&gt;(this Task first, Func&lt;T2&gt; next);        <br />public noise Task&lt;T2&gt; Then&lt;T2&gt;(this Task first, Func&lt;Task&lt;T2&gt;&gt; next);        </p>
<p>public noise Task Then&lt;T1&gt;(this Task&lt;T1&gt; first, Action&lt;T1&gt; next);        <br />public noise Task Then&lt;T1&gt;(this Task&lt;T1&gt; first, Func&lt;T1,Task&gt; next);        <br />public noise Task&lt;T2&gt; Then&lt;T1,T2&gt;(this Task&lt;T1&gt; first, Func&lt;T1,T2&gt; next);        <br />public noise Task&lt;T2&gt; Then&lt;T1,T2&gt;(this Task&lt;T1&gt; first, Func&lt;T1, Task&lt;T2&gt;&gt; next);</p>
</blockquote>
<p><strong>Sequence</strong></p>
<p>With much methods, we crapper create added abstractions for sequential processing as well.&#160; Let’s feature we did hit an feat for an added digit of the above overloads:</p>
<blockquote><pre>public noise Task Then(this Task first, Func&lt;Task&gt; next){&#160;&#160;&#160; if (first == null) intercommunicate newborn ArgumentNullException(&quot;first&quot;);&#160;&#160;&#160; if (next == null) intercommunicate newborn ArgumentNullException(&quot;next&quot;);

&#160;&#160;&#160; var tcs = newborn TaskCompletionSource&lt;object&gt;();&#160;&#160;&#160; first.ContinueWith(delegate&#160;&#160;&#160; {&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions);&#160;&#160;&#160;&#160;&#160;&#160;&#160; added if (first.IsCanceled) tcs.TrySetCanceled();&#160;&#160;&#160;&#160;&#160;&#160;&#160; else&#160;&#160;&#160;&#160;&#160;&#160;&#160; {&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; try&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; var t = next();&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (t == null) tcs.TrySetCanceled();&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; added t.ContinueWith(delegate&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions);&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; added if (t.IsCanceled) tcs.TrySetCanceled();&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; added tcs.TrySetResult(null);&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously);&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; grownup (Exception exc) { tcs.TrySetException(exc); }&#160;&#160;&#160;&#160;&#160;&#160;&#160; }&#160;&#160;&#160; }, TaskContinuationOptions.ExecuteSynchronously);&#160;&#160;&#160; convey tcs.Task;}</pre>
</blockquote>
<p>We crapper locate a Sequence method on crowning of this as follows:</p>
<blockquote>
<pre>public noise Task Sequence(params Func&lt;Task&gt; [] actions){&#160;&#160;&#160; Task terminal = null;&#160;&#160;&#160; foreach (var state in actions)&#160;&#160;&#160; {        terminal = (last == null) ? Task.Factory.StartNew(action).Unwrap() : last.Then(action);&#160;&#160;&#160; }&#160;&#160;&#160; convey last;}</pre>
</blockquote>
<p>and with much a Sequence method, we’re today healthy to indite a ordered of lambdas that module be computerized asynchronously digit after the other, e.g.</p>
<blockquote>
<p>Task&lt;string&gt; aResult = null, bResult = null, cResult = null;<br />
      <br />Sequence(</p>
<p>&#160;&#160;&#160; () =&gt; { convey aResult = DoAAsync(input); },</p>
<p>&#160;&#160;&#160; () =&gt; { convey bResult = DoBAsync(aResult.Result); },</p>
<p>&#160;&#160;&#160; () =&gt; { convey cResult = DoCAsync(bResult.Result); });</p>
</blockquote>
<p><strong>Iterate</strong></p>
<p>We crapper physique another engrossing combinators for sequential processing, including digit that takes plus of C# iterators.&#160; There are individual favourite frameworks that ingest C# iterators to intend anachronic processing, and the aforementioned gimmick engaged in those crapper be utilised with tasks.&#160; Here’s a base warning of much a driver:</p>
<blockquote>
<pre>public noise Task Iterate(IEnumerable&lt;Task&gt; asyncIterator){&#160;&#160;&#160; if (asyncIterator == null) intercommunicate newborn ArgumentNullException(&quot;asyncIterator&quot;);

&#160;&#160;&#160; var functionary = asyncIterator.GetEnumerator();&#160;&#160;&#160; if (enumerator == null) intercommunicate newborn InvalidOperationException(&quot;Invalid enumerable - GetEnumerator returned null&quot;);

&#160;&#160;&#160; var tcs = newborn TaskCompletionSource&lt;object&gt;();&#160;&#160;&#160; tcs.Task.ContinueWith(_ =&gt; enumerator.Dispose(), TaskContinuationOptions.ExecuteSynchronously);

&#160;&#160;&#160; Action&lt;Task&gt; recursiveBody = null;&#160;&#160;&#160; recursiveBody = assign {&#160;&#160;&#160;&#160;&#160;&#160;&#160; essay {&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (enumerator.MoveNext()) enumerator.Current.ContinueWith(recursiveBody, TaskContinuationOptions.ExecuteSynchronously);&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; added tcs.TrySetResult(null);&#160;&#160;&#160;&#160;&#160;&#160;&#160; }&#160;&#160;&#160;&#160;&#160;&#160;&#160; grownup (Exception exc) { tcs.TrySetException(exc); }&#160;&#160;&#160; };

&#160;&#160;&#160; recursiveBody(null);&#160;&#160;&#160; convey tcs.Task;}</pre>
</blockquote>
<p>This Iterate method accepts an enumerable of tasks.&#160; This enumerable needs to be lazy, much that the incoming duty isn’t generated until MoveNext is titled to regain it; this is meet the activity we’ll mostly intend with a C# iterator (and a VB iterator in Async CTP, but if you hit the Async CTP, you should meet ingest <em>await</em> as titled discover at the first of this post).&#160; The Iterate method retrieves an functionary and begins by occupation MoveNext on it.&#160; The duty returned from the functionary as Current then has a postscript crooked up to it which, when the retrieved duty completes, starts that impact again, occupation MoveNext on the enumerator, hooking up a continuation, and so on.&#160; Only erst MoveNext throws an omission or returns simulated does this impact end.&#160; With much an Iterate method in place, we crapper today writing our warning distribution with a method aforementioned this:</p>
<blockquote>
<p>IEnumerable&lt;Task&gt; DoExample(string input)<br />
      <br />{</p>
<p>&#160;&#160;&#160; var aResult = DoAAsync(input);</p>
<p>&#160;&#160;&#160; consent convey aResult;</p>
<p>&#160;&#160;&#160; var bResult = DoBAsync(aResult.Result);</p>
<p>&#160;&#160;&#160; consent convey bResult;</p>
<p>&#160;&#160;&#160; var cResult = DoCAsync(bResult.Result);</p>
<p>&#160;&#160;&#160; consent convey cResult;</p>
<p>&#160;&#160;&#160; …</p>
<p>}</p>
</blockquote>
<p>which we then advert with cipher like:</p>
<blockquote>
<p>Task t = Iterate(DoExample(“42”));</p>
</blockquote>
<p>There are of instruction whatever variations on the Iterate feat you could easily add.&#160; For example, you strength poverty the process to kibosh if a retrieved duty ends in the faulted state; that crapper be realised with whatever secondary modifications to the recursiveBody function.</p>
<p><strong>LINQ</strong></p>
<p>Getting slightly more wacky (but ease within the demesne of reasonable), we crapper apply the C# and VB LINQ structure to also impart sequential processing.&#160; The C# and VB compilers are pattern-based in their hold of the .NET accepted ask operators, allowing you to ingest from, select, and so on with capricious accumulation types as daylong as methods matched the correct mode are exposed.&#160; We can, for example, compel an pertinent SelectMany cause as an extensions method on crowning of Task&lt;TResult&gt;:</p>
<blockquote>
<pre>static collection Extensions{&#160;&#160;&#160; open noise Task&lt;TResult&gt; SelectMany&lt;TSource, TCollection, TResult&gt;(&#160;&#160;&#160;&#160;&#160;&#160;&#160; this Task&lt;TSource&gt; source,&#160;&#160;&#160;&#160;&#160;&#160;&#160; Func&lt;TSource, Task&lt;TCollection&gt;&gt; collectionSelector,&#160;&#160;&#160;&#160;&#160;&#160;&#160; Func&lt;TSource, TCollection, TResult&gt; resultSelector)&#160;&#160;&#160; {&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (source == null) intercommunicate newborn ArgumentNullException(&quot;source&quot;);&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (collectionSelector == null) intercommunicate newborn ArgumentNullException(&quot;collectionSelector&quot;);&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (resultSelector == null) intercommunicate newborn ArgumentNullException(&quot;resultSelector&quot;);

&#160;&#160;&#160;&#160;&#160;&#160;&#160; convey source.ContinueWith(t =&gt;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; convey collectionSelector(t.Result).&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ContinueWith(c =&gt; resultSelector(t.Result, c.Result), TaskContinuationOptions.NotOnCanceled);&#160;&#160;&#160;&#160;&#160;&#160;&#160; }, TaskContinuationOptions.NotOnCanceled).Unwrap();&#160;&#160;&#160; }}</pre>
</blockquote>
<p>and with that, we crapper then re-implement our warning warning with cipher like:</p>
<blockquote>
<pre>var termination = from aResult in DoAAsync(&quot;42&quot;)&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; from bResult in DoBAsync(aResult)&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; from cResult in DoCAsync(bResult)&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; superior cResult;</pre>
</blockquote>
<p>An feat of a clump of the LINQ operators targeting tasks is acquirable as conception of the Parallel Extensions Extras send at <a href="http://code.msdn.microsoft.com/ParExtSamples">http://code.msdn.microsoft.com/ParExtSamples</a>.&#160; If instead we were to apply the Reactive Extensions acquirable for download from the DevLabs site, we crapper apply the ToObservable spreading method it provides for Task&lt;TResult&gt;, and then apply Rx’s burly LINQ feat to do the aforementioned thing, e.g.</p>
<blockquote>
<p>var termination = from aResult in DoAAsync(&quot;42&quot;).ToObservable()<br />
      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; from bResult in DoBAsync(aResult).ToObservable()</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; from cResult in DoCAsync(bResult).ToObservable()</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; superior cResult;</p>
</blockquote>
<p><strong>F# Async Workflows</strong></p>
<p>Out-of-the-box in Visual Studio 2010, F# supports anachronic workflows and has built-in aptitude for awaiting tasks.&#160; This allows you to indite the warning warning with cipher like:</p>
<blockquote>
<p>let warning = async {<br />
      <br />&#160;&#160;&#160; let! aResult = Async.AwaitTask DoAAsync()</p>
<p>&#160;&#160;&#160; let! bResult = Async.AwaitTask DoBAsync()</p>
<p>&#160;&#160;&#160; let! cResult = Async.AwaitTask DoCAsync()</p>
<p>&#160;&#160;&#160; …</p>
<p>}</p>
</blockquote>
<p><strong>Summary</strong></p>
<p>As you crapper see, there are whatever multipurpose and engrossing structure to attain sequential, anachronic processing using Tasks.&#160; Eventually when built-in module hold is acquirable for awaiting tasks, that module be the easiest and the advisable move for nonindustrial anachronic cipher of this nature.&#160; In the meantime, you crapper essay discover much hold in the <a href="http://msdn.com/vstudio/async">Async CTP</a>, and you crapper ingest another techniques as described in this journal locate to attain kindred kinds of processing today, assured that you’ll be healthy to update that cipher in the forthcoming with the more coercive module capabilities when they’re available.</p>
<p>Happy coding!</p>
<div></div>
<p><img src="http://blogs.msdn.com/aggbug.aspx?PostID=10094564" width="1" height="1" title="Processing Sequences of Asynchronous Operations with Tasks" alt=" Processing Sequences of Asynchronous Operations with Tasks" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.feedpals.com/processing-sequences-of-asynchronous-operations-with-tasks.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NEW FEATURE? :: DELAYED CANCELLATION</title>
		<link>http://www.feedpals.com/new-feature-delayed-cancellation.html</link>
		<comments>http://www.feedpals.com/new-feature-delayed-cancellation.html#comments</comments>
		<pubDate>Thu, 04 Nov 2010 20:53:00 +0000</pubDate>
		<dc:creator></dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/shahidsi/public_html/feedpals.com/wp-content/plugins/autometa/autometa.php</b> on line <b>300</b><br />
		<category><![CDATA[.NET Help]]></category>
		<category><![CDATA[-net-4]]></category>
		<category><![CDATA[new feature?]]></category>
		<category><![CDATA[parallel-extensions]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://www.feedpals.com/new-feature-delayed-cancellation.html</guid>
		<description><![CDATA[ &#160; We&#8217;re interested in adding support for scheduling cancellation.&#160; For example: &#160; // Create a token source that will Cancel() after a delay var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); // And/or schedule a Cancel() call cts.CancelAfter(TimeSpan.FromMilliseconds(100)); We&#8217;ve heard from many folks that this is a desired feature and have found good uses for it ourselves.&#160; Interestingly, we would also allow CancelAfter() to be called multiple times to reset the delay (provided the token source was not already canceled, of course).&#160; One could also effectively cancel the cancellation by calling CancelAfter() with TimeSpan.MaxValue. &#160; One potential issue we&#8217;ve been thinking through is whether/how to deal with exceptions that fly out of user-registered delegates.&#160; Recall that we strongly discourage throwing exceptions from callbacks registered with a CancellationToken, though it is possible to handle such exceptions today: &#160; cts.Token.Register(() =&#62; { throw new Exception(&#8220;HA!&#8221;); }); try { cts.Cancel(); } // invokes the callbacks catch { // Caught it! } However, if you use this new feature to cancel asynchronously, you won&#8217;t ever have a chance to handle the exception, and it would likely bring down your application.&#160; Some are of the opinion that we need not do anything about this, but we&#8217;ve been brainstorming potential solutions anyway.&#160; We&#8217;re definitely curious what you think =).&#160; Feel free to answer these questions if you want: What do you think about unhandled exceptions flying out of user-created token callbacks?&#160; Should we support this use case? Any feedback about the general feature? Thanks! &#160; ]]></description>
			<content:encoded><![CDATA[<p>
<p>&nbsp;</p>
<p>We&rsquo;re fascinated in adding hold for scheduling<br />
cancellation.&nbsp; For example:</p>
<p>&nbsp;</p>
<p><span>// Create a<br />
token maker that module Cancel() after a delay<br />
var cts = newborn CancellationTokenSource(TimeSpan.FromMilliseconds(100));</span></p>
<p><span><br /></span></p>
<p><span>// And/or<br />
schedule a Cancel() call<br />
cts.CancelAfter(TimeSpan.FromMilliseconds(100));</span></p>
<p><span><br /></span></p>
<p>We&rsquo;ve heard from some folks that this is a desirable feature<br />
and hit institute beatific uses for it ourselves.&nbsp;<br />
Interestingly, we would also earmark CancelAfter() to be titled multiple<br />
times to set the retard (provided the minimal maker was not already canceled,<br />
of course).&nbsp; One could also effectively<br />
cancel the cancellation by occupation CancelAfter() with TimeSpan.MaxValue.</p>
<p>&nbsp;</p>
<p>One possibleness supply we&rsquo;ve been intellection finished is whether/how<br />
to care with exceptions that control discover of user-registered delegates.&nbsp; Recall that we strongly advise throwing<br />
exceptions from callbacks qualified with a CancellationToken, though it is<br />
possible to appendage much exceptions today:</p>
<p>&nbsp;</p>
<p><span>cts.Token.Register(()<br />
=&gt; { intercommunicate newborn Exception(&ldquo;HA!&rdquo;); });</p>
<p>try { cts.Cancel(); } // invokes the callbacks<br />
catch { // Caught it! }</span></p>
<p><span><br /></span></p>
<p>However, if you ingest this newborn feature to cancel<br />
asynchronously, you won&rsquo;t ever hit a quantity to appendage the exception, and it<br />
would probable alter downbound your application.&nbsp;<br />
Some are of the instrument that we requirement not do anything most this, but<br />
we&rsquo;ve been brainstorming possibleness solutions anyway.&nbsp; We&rsquo;re definitely peculiar what you think<br />
=).&nbsp; Feel liberated to respond these questions<br />
if you want:</p>
<ol>
<li>What do you conceive most unhandled exceptions<br />
flying discover of user-created minimal callbacks?&nbsp;<br />
Should we hold this ingest case?</li>
<li>Any feedback most the generalized feature?</li>
</ol>
<p>Thanks!</p>
<p>&nbsp;</p>
<div></div>
<p><img src="http://blogs.msdn.com/aggbug.aspx?PostID=10086328" width="1" height="1" title="New Feature? :: Delayed cancellation" alt=" New Feature? :: Delayed cancellation" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.feedpals.com/new-feature-delayed-cancellation.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

