task net 4 5

  • Latest Articles
  • Top Articles
  • Posting/Update Guidelines
  • Article Help Forum

task net 4 5

  • View Unanswered Questions
  • View All Questions
  • View C# questions
  • View C++ questions
  • View Javascript questions
  • View PHP questions
  • View Python questions
  • CodeProject.AI Server
  • All Message Boards...
  • Running a Business
  • Sales / Marketing
  • Collaboration / Beta Testing
  • Work Issues
  • Design and Architecture
  • Artificial Intelligence
  • Internet of Things
  • ATL / WTL / STL
  • Managed C++/CLI
  • Objective-C and Swift
  • System Admin
  • Hosting and Servers
  • Linux Programming
  • .NET (Core and Framework)
  • Visual Basic
  • Web Development
  • Site Bugs / Suggestions
  • Spam and Abuse Watch
  • Competitions
  • The Insider Newsletter
  • The Daily Build Newsletter
  • Newsletter archive
  • CodeProject Stuff
  • Most Valuable Professionals
  • The Lounge  
  • The CodeProject Blog
  • Where I Am: Member Photos
  • The Insider News
  • The Weird & The Wonderful
  • What is 'CodeProject'?
  • General FAQ
  • Ask a Question
  • Bugs and Suggestions

task net 4 5

Improved Multi-Threading Support in .NET 4.5

task net 4 5

  • Download source code - 3.44 KB

Introduction

This is a quick tour of the new language support for multi-threaded programming coming in .NET 4.5. These examples were programmed using the Visual Studio 11 developer preview released back in September.

Multi-Threaded Evolution

Like Java, C# has had threading support since the beginning. In the early days, this meant having a set of synchronization classes in the CLR, along with the lock statement. While this was better than having to call a system library, the difficulty of writing threaded code was still too high for most developers and projects.

But multi-threaded programming is increasingly important because multiple parallel cores, rather than faster clock speeds, is how computers are evolving into the future. As a result, Microsoft has continually enhanced threading support in .NET in almost every release. .NET 4 introduced the Task Parallel Library (TPL), a major conceptual step forward. .NET 4.5 builds on this by integrating tasks directly into the language.

Tasks not Threads

This latest approach to threading is to not think about or deal with threads at all! Instead, you program with tasks, where a task is simply a value (data) that will be available at a later time (technically, a “future”). How does this help?

The idea is to make parallel code look and act, as much as possible, like sequential code. Consider this function, which calls two other long running functions before displaying the result:

The problem with this code is that GetAnotherExpensiveString can’t begin until GetExpensiveString completes. Also, the calling code (and the rest of the program) is stopped until both long-running functions return.

For the purposes of this simple example, the 'expensive' methods just mark time:

In .NET 4.5, this code becomes:

We’ve introduced two keywords, and one naming convention, to indicate the places where control can switch to another thread and then revert back.

Let’s look at the time-consuming methods first. They have been changed to return Task<string> instead of string , and by convention, their names are now suffixed with ‘Async’. So instead of returning the string we want, they are returning a Task object, a kind of proxy or promise that says “I’ll give the string to you later.” Since my long running functions don't access any shared variables, there are no locking issues, so the asynchronous versions just call the synchronous functions inside a task.

But I’m still assigning the return values to string variables. This works because of the await keyword in front of each call. This essentially says “whenever this task completes, come back here, assign its value, and continue on.”

The other change is to the function signature: we’ve decorated the function with the async keyword, changed the return value to Task , and appended the “Async” suffix, again by convention. These changes tell the compiler and other programmers that this function contains asynchronous control flow.

Asynchronous Control Flow

Our function looks pretty similar (that’s the idea) but behaves quite differently. When you called Function , you sat for a while and it didn’t return until the line was written to the console. In FunctionAsync , the call to GetExpensiveStringAsync starts a task on another thread and then immediately returns, where control flow on this thread continues.

Sometime later, the task completes, and the CLR resumes execution back in FunctionAsync . In this case, the process repeats: the CLR starts another background task, and still later returns to finally execute the console write.

Note that unlike with Function , the caller to FunctionAsync continues executing after the quick return. You can now do other work in parallel with FunctionAsync , and sync up with him if needed. Here is the revised calling code:

So what’s going on to make all of this work?

Under the covers, C# has turned our simple function into a state machine, and created hidden classes that essentially save the call stack on the heap. Each await expression marks a place where the function can switch threads or “pause”, and then resume later on.

This is all conceptually simple but quite complex in the details. This is especially true with resuming complex flow of control (think nested ifs and loops) and propagating exceptions out. There are similarities to how the yield statement works in iterators, and this also leverages the capture of local variables in closures first introduced with lambda expressions.

Even More Asynchronous

We’ve achieved some parallel execution here, but we can do better. We’ve moved GetExpensiveString to the background so that other processing can go on in parallel. But as currently structured, GetAnotherExpensiveString can’t start executing until after GetExpensiveString finishes. This final version fixes that problem:

In order to get both time consuming functions to run in parallel, we have to deal more directly with the task objects. Here, we use the task WhenAll method to wait until all of the other tasks finish. The .NET 4.5 Task API adds several new methods that make it very convenient to compose and synchronize tasks.

Don’t be fooled: there is no magic here. Asynchronous programming is still difficult and complex. This simple example program ends up running on four different threads. It is much less repeatable now as it’s subject to timing variations from run to run, especially on multi-core processors.

Sequential code execution is a fundamental expectation burned into the brain of every programmer. Asynchronous programming will always be difficult precisely because it violates this basic assumption. It forces you to think differently about your programs. It took me about a day of messing around (struggling) with these new features before they started to click into place. In that sense, it is probably similar to learning LINQ or lambda expressions. As always, Microsoft’s tool, sample, and documentation support is there to help get you up to speed.

It’s worth the effort because the benefits are so significant: in this example, each of the expensive functions takes five seconds to execute, and the final parallel program takes slightly longer than five seconds total, as compared to ten for the original version. Besides the speed up, the real win in a production program is the ability to keep the UI live and responsive.

The new .NET asynchronous programming model is a big step forward. As with other areas, it allows you to think and program at a higher level while it manages the details. There’s a lot of sophisticated machinery down in the compiler and run-time to pull this off, and that’s as it should be.

  • October 27, 2011 - Revised to incorporate feedback.
  • October 26, 2011 - Original article.

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Comments and Discussions

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

task net 4 5

task net 4 5

01 July 2013

53330 views

Printer friendly version

The overhead of async/await in NET 4.5

The support for asynchronous operations in .NET 4.5 has made it much easier to create easily-intelligible asynchronous methods that avoid blocking. However, async/wait isn't cost-free in terms of CPU overhead. How best to judge when to use it? Chris Hurley explains.

ANTS Performance Profiler 9 now includes async profiling for database calls.

Async/await is great for avoiding blocking while potentially time-consuming work is performed in a .NET application, but there are overheads associated with running an async method: the current execution context has to be captured, there is a thread transition, and a state machine is built through which your code runs. The cost of this is comparatively negligible when the asynchronous work takes a long time, but it’s worth keeping in mind.

Support for the async and await contextual keywords is one of the most convenient new features in .NET 4.5. It’s always been possible to write asynchronous code, of course, but async / await allows it to be written in a relatively straightforward manner which neatly expresses the intention of the code, and means that it isn’t necessary to write separate continuation methods. As long as you have a Task (or anything else that implements the Awaitable pattern) that you can await on, the compiler can automatically set up the environment on which you can wait for it to complete, and then continue execution once the work is done, all without blocking the calling thread unnecessarily.

In order to provide a responsive and smooth interface, particularly on touch and gesture devices, it is particularly important  to avoiding blocking the UI thread. This was a central focus for Microsoft during the development of the WinRT API, and they ensured that any APIs that may take longer than 50ms to execute would only be available in an asynchronous form.

Of course, you could use async / await regardless of the amount of time that the method call is likely to take. However, the ease with which it’s possible to make an operation asynchronous in your code hides the work that’s being done behind the scenes. As soon as the compiler sees the async keyword next to a method, it replaces your method with the async state machine. If you write a simple method that looks like:

… then the compiler generates the following (obtained by setting .NET Reflector to .NET 4.0 mode, so it doesn’t attempt to understand the async implementation):

Calling the method now requires creating a state machine and building a Task to contain the work that goes on within it: none of the code in the original method is referenced here. Setting it all up the first time is a relatively complex operation ( Figure 1):

1827-clip_image001.png

Figure 1: Framework methods required to initialize an example async method

Despite this async method being relatively simple, ANTS Performance Profiler shows that it’s caused over 900 framework methods to be run in order to initialize it and the work it does the first time that it’s run.

1827-clip_image002-630x197.png

Figure 2: The framework methods include those called by Task.Run and several System.Runtime.CompilerServices methods

The largest proportion of these methods is made up of those involved in starting a new Task in which to do the asynchronous work, due to the call to Task.Run (Figure 2). This is not inherently due to the use of async / await , but it should be noted that moving the asynchronous work onto another thread in some way like this is required if the original thread is to be unblocked: otherwise, the work is done synchronously, despite the use of the async / await keywords. Even if the method never hits an await statement or starts a new Task , there is still overhead, as building the async method involves getting the execution context and synchronization context and therefore examining the stack. Fortunately, the context is cached, and so the overhead on subsequent calls is much lower.

The synchronization context is necessary to ensure that the continuation code after await statements is called in the same context as the original code. This is important if, for example, the method was originally called from the UI thread and will update the UI when the asynchronous task is complete, but is not always necessary or desirable. Calling Task.ConfigureAwait(false) prevents the restoration of the synchronization context, and should be used when it is not required to return to the original context.

So, given that the compiler has replaced the original contents of the AsyncMethod() method, where did it move it to? It’s ended up in the MoveNext() method of the state machine. For example, after doing some initial set-up, it runs InitialWork() :

Disabling Async Mode in ANTS Performance Profiler 8 exposes this implementation detail:

1827-clip_image003.png

Figure 3: Disabling Async Mode in ANTS Performance Profiler 8 shows the internal MoveNext methods and the switch to the thread pool

In this example, the initial work was done on the originating thread, but switched over to a thread-pool thread in order to do the async work (see Figure 3). Execution then returns to the state machine, which moves on and executes the final part of the method. The more await statements there are, the more movements through the state machine are required.

So what is the overhead of all this initialization, and how much persists on subsequent calls? Here, I’ve set up a simple WPF application to initiate some synchronous and asynchronous calls in response to button clicks. The potentially-asynchronous method, DoAsyncWork() , returns in 1ms. The first call to this method takes just over 1ms when called synchronously (Figure 4):

1827-clip_image004-630x145.png

Figure 4: ANTS Performance Profiler 8 results for initial synchronous run of an example method

However, when going through the async state machine, the total time for the task to complete is over 70ms. Indeed, it takes 45ms just to get to the await statement, at which point the calling thread is unblocked (Figure 5):

1827-clip_image005-630x133.png

Figure 5: Async Mode results for the first async run of an example method, where the Total time column shows the total time required for the async method to complete

There’s a lot of initialization happening here, and fortunately the overhead is much lower on subsequent runs, as we’ll see in the next example. When these methods are called 1000 times in a loop, the synchronous calls complete in barely any more time than the 1000ms the work itself would take (Figure 6):

1827-clip_image006-630x112.png

Figure 6: Results after running an example method synchronously in a loop 1000 times

Once an async method is called in a loop to call the same function, however, the total time increases due to the additional overhead. In this particular example, involving both the use of async and scheduling tasks to the thread pool, this increase is around 150ms over the 1000ms duration for the work itself, after running the method once to prevent JIT and thread pool initialization overhead (Figure 7). That’s an increase of around 15%.

1827-clip_image007-630x112.png

Figure 7: Results after running the example method asynchronously in a loop 1000 times

The continued overhead of async / await and the dispatching of individual tasks to the thread pool is actually quite small given the amount of work that’s being done, and there’s certainly no reason not to use it for methods that are potentially slow, especially given the benefits of running such code asynchronously.  However, the overhead isn’t zero, so if you’re looking to maximize performance of frequently-called code you may want to avoid the use of async / await for very short methods, especially those called in a loop – instead, wrap the async code around potentially slow methods or larger units of work where the added overhead is negligible.

Avoid using async/await for very short methods or having await statements in tight loops (run the whole loop asynchronously instead). Microsoft recommends that any method that might take longer than 50ms to return should run asynchronously, so you may wish to use this figure to determine whether it’s worth using the async/await pattern.

Subscribe for more articles

Fortnightly newsletters help sharpen your skills and keep you ahead, with articles, ebooks and opinion to keep you informed.

Rate this article

task net 4 5

Chris Hurley

Chris is a Software Engineer with the .NET Developer Tools Division at Red Gate. He obtained a PhD in Biology before moving into professional software development

Follow Chris Hurley via

View all articles by Chris Hurley

Load comments

Related articles

task net 4 5

Inline PDF Viewer in an Angular App? Now you can

task net 4 5

The Zen of Code Reviews: Review As If You Own the Code

task net 4 5

C# Cancellation Tokens in AWS

Scott Hanselman

How to run background tasks in asp.net.

A few years back Phil Haack wrote a great article on the dangers of recurring background tasks in ASP.NET . In it he points out a few gotchas that are SO common when folks try to do work in the background. Read it, but here's a summary from his post.

  • An unhandled exception in a thread not associated with a request will take down the process.
  • If you run your site in a Web Farm, you could end up with multiple instances of your app that all attempt to run the same task at the same time.
  • The AppDomain your site runs in can go down for a number of reasons and take down your background task with it.

If you think you can just write a background task yourself, it's likely you'll get it wrong. I'm not impugning your skills, I'm just saying it's subtle . Plus, why should you have to?

There's LOT of great ways for you to do things in the background and a lot of libraries and choices available.

Some ASP.NET apps will be hosted in IIS in your data center and others will be hosted in the Azure cloud. The spectrum of usage is roughly this, in my opinion:

  • used for writing background tasks in your ASP.NET website
  • A formal Azure feature used for offloading running of background tasks outside of your Website and scale the workload
  • scale the background processing workload independently of your Website and you need control over the machine

There's lots of great articles and videos on how to use Azure WebJobs , and lots of documentation on how Worker Roles in scalable Azure Cloud Services work, but not a lot about how your hosted ASP.NET application and easily have a background service. Here's a few.

WebBackgrounder

As it says " WebBackgrounder is a proof-of-concept of a web-farm friendly background task manager meant to just work with a vanilla ASP.NET web application." Its code hasn't been touched in years, BUT the WebBackgrounder NuGet package has been downloaded almost a half-million times.

The goal of this project is to handle one task only, manage a recurring task on an interval in the background for a web app.

If your ASP.NET application just needs one background task to runs an a basic scheduled interval, than perhaps you just need the basics of WebBackgrounder.

Built in: QueueBackgroundWorkItem - Added in .NET 4.5.2

Somewhat in response to the need for WebBackgrounder, .NET 4.5.2 added QueueBackgroundWorkItem as a new API . It's not just a "Task.Run," it tries to be more:

QBWI schedules a task which can run in the background, independent of any request. This differs from a normal ThreadPool work item in that ASP.NET automatically keeps track of how many work items registered through this API are currently running, and the ASP.NET runtime will try to delay AppDomain shutdown until these work items have finished executing.

It can try to delay an AppDomain for as long as 90 seconds in order to allow your task to complete. If you can't finish in 90 seconds, then you'll need a different (and more robust, meaning, out of process) technique.

The API is pretty straightforward, taking  Func<CancellationToken, Task>. Here's an example that kicks of a background work item from an MVC action:

FluentScheduler

FluentScheduler is a more sophisticated and complex scheduler that features a (you guessed it) fluent interface. You have really explicit control over when your tasks run.

FluentScheduler also embraces IoC and can easily plug into your favorite Dependency Injection tool of choice by just implementing their ITaskFactory interface.

Quartz.NET is a .NET port of the popular Java job scheduling framework of the (almost) same name. It's very actively developed. Quartz has an IJob interface with just one method, Execute, to implement.

Then, inside your Application_Start, you call JobScheduler.Start(). There's a great getting started article on Quartz at Mikesdotnetting you should check out.

And last but definitely not least, the most polished (IMHO) of the group, Hangfire by @odinserj . It's a fantastic framework for background jobs in ASP.NET. It's even optionally backed by Redis, SQL Server, SQL Azure, MSMQ, or RabbitMQ for reliability.

The Hangfire documentation is amazing , really. Every open source project's document should be this polished. Heck, ASP.NET's documentation should be this good.

The best feature from Hangfire is its built in /hangfire dashboard that shows you all your scheduled, processing, succeeded and failed jobs. It's really a nice polished addition.

image

You can enqueue "fire and forget" jobs easily and they are backed by persistent queues:

You can delay them...

Or great very sophisticated CRON style recurrent tasks:

Hangfire is just a joy.

Check out the Hangfire Highlighter Tutorial for a sophisticated but easy to follow real-world example.

There's a rich ecosystem out there ready to help you with your background tasks. All these libraries are excellent, are open source, and are available as NuGet Packages .

Did I miss your favorite? Sound off in the comments!

Sponsor: Many thanks to my friends at Raygun for sponsoring the feed this week. I *love* Raygun and use it myself. It's amazing. Get notified of your software’s bugs as they happen! Raygun.io has error tracking solutions for every major programming language and platform - Start a free trial in under a minute!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook

Is running background tasks in your ASP.NET process the wrong approach? I would always be very uncomfortable doing this.
  • Error handling – logging using your favorite implementation, including Elmah), automatic retries with increasing intervals.
  • Multiple instances (web farms, web gardens) – queues where only one consumer can fetch a job, distributed locks.
  • App domain unloads . This is the most complex thing. In case of graceful termination all jobs are being returned to their queues programmatically. In case of unexpected termination they are being returned after some interval (this interval can be eliminated by using MSMQ or RabbitMQ) – Hangfire guarantees that every queued background job will be processed anyway when there is at least one running Hangfire Server.
Who then becomes responsible for maintaining the background tasks?

task net 4 5

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

task net 4 5

  • Network Programming
  • Windows Programming
  • Visual Studio
  • Visual Basic

Logo

How to Create an Asynchronous HTTP Handler in ASP.NET 4.5

Bipin Joshi

Introduction

The ability to create HTTP handlers is not new to ASP.NET. However, ASP.NET 4.5 makes it easy for you to create asynchronous HTTP handlers with the new async/await keywords and Tasks. This article illustrates how an asynchronous HTTP handler can be created and consumed in an ASP.NET 4.5 web application.

Creating HTTP Handlers in ASP.NET

Traditionally HTTP handlers are classes that implement the IHttpHandler interface. You can also create an asynchronous HTTP handler by implementing the IHttpAsyncHandler interface. Asynchronous HTTP handlers are advantageous in situations where asynchronous processing can improve the overall performance of the application. The IHttpAsyncHandler interface requires you to write methods of the form BeginProcessRequest() and EndProcessRequest() methods. In ASP.NET 4.5 you can use the new async/await keywords and Tasks to achieve the same effect with simplified design.  Under ASP.NET 4.5 you can create a class that inherits from the HttpTaskAsyncHandler class and then override certain methods (as discussed later in this article).

NOTE: Detailed discussion of async/await keywords and Tasks is beyond the scope of this article. You may read Working with Asynchronous Operations in ASP.NET 4.5 Web Forms for the basic understanding of these concepts.

Sample Asynchronous HTTP Handler

To understand how asynchronous HTTP handlers are created in ASP.NET 4.5, let’s develop a simple example. Suppose that you have an ASP.NET web site with one or more web forms. On each of the web forms you wish to display advertisements. The advertisements are not statically placed on the web forms. They reside in a SQL Server database and at runtime you need to fetch them so as to render them onto the pages. Additionally, you also need to track the impressions each advertisement is receiving.

The following figure shows the Entity Framework for the sample database tables Ads and AdStats.

The Entity Framework

The Entity Framework

As you can see the Ads table has only two columns, viz. Id and Markup. The Markup column contains the HTML markup of the advertisement. The AdStats table stores information about ad impressions such as UserIP, UserAgent and TargetUrl.

To display an advertisement on web forms and to track the ad statistics you will create an asynchronous HTTP handler. In this specific scenario, creating an asynchronous HTTP handler rather than a synchronous one is beneficial because the ads are independent of the web form content and can be processed asynchronously. To create the asynchronous HTTP handler add a new Generic Handler (*.ashx) to the web application.

Add a new Generic Handler

Add a new Generic Handler

Change the default definition of the Generic Handler class as shown below:

As shown above the MyHandler class inherits from the HttpTaskAsyncHandler base class. The HttpTaskAsyncHandler class is provided by ASP.NET 4.5 and you need to override its ProcessRequestAsync() method. The following code shows a sample implementation of the overridden method:

 As you can see the ProcessRequestAsync() method is an asynchronous method. Inside ProcessRequestAsync(), details about the web form requesting an advertisement are captured. These details include the user’s IP address, the URL of the target web form and the requesting browser. The code then gets the details of advertisement from the database by calling the GetAdAsync() method. It also saves the ad statistics to the database by calling the SetStatsAsync() method.

The GetAdAsync() and SetStatsAsync() methods are quite similar in nature and are shown below.

Both of these methods start a new Task and run the actual database access code on it using two helper methods: GetAdFromDb() and SaveStatsToDb(). These helper methods are shown below.

The GetAdFromDb() method simply retrieves the first record from the Ads table. In a real world situation you will have some ad selection logic here. It then returns the ad Markup to the caller. Notice that the GetAdFromDb() method introduces a delay of 5 seconds by calling the Sleep() method. This is done purely for the purpose of testing and you can remove this line once the application is complete. The SaveStatsToDb() method stores the target URL, user’s IP and user agent (browser) to the AdStats table.

Using the Sample HTTP Handler in a Web Form

Now that your asynchronous HTTP handler is ready, let’s see how it can be used in a web form. Add a web form to the web application and place a <script> tag in it as shown below.

As you can see the <script> tag points to the MyHandler.ashx, the asynchronous HTTP handler you developed in the previous section. It also passes the Request.Path of the current web form in a querystring parameter. This way you are making a call to the asynchronous HTTP handler where the <script> tag is placed.

Before running the web form, add some advertisement data in the Ads table and then run the web form. The following figure shows a sample run of the web form.

Sample run of a web form

Sample run of a web form

As you can see from the above figure the text “Hello World!” is part of the web form whereas the text “This is an advertisement!” is the part of an advertisement and is stored in the database. Also notice that when you run this web form “Hello World!” is displayed immediately and the advertisement is displayed after 5 seconds due to the delay introduced in the code. After running the web form check the database to verify the ad statistics are stored as expected.

ASP.NET 4.5 allows you to create asynchronous HTTP handlers easily. An asynchronous HTTP handler is a class that inherits from the HttpTaskAsyncHandler base class. This article illustrated how an asynchronous HTTP handler can be created and consumed in a web forms application.

Bipin Joshi

More by Author

Understanding routing in asp.net core mvc, creating a web api in asp.net core, performing database operations using entity framework core and asp.net core, your first asp.net core 1.0 app, news & trends, different types of jit compilers in .net, middleware in asp.net core, intro to intel onedal and ml.net, get the free newsletter.

Subscribe to Developer Insider for top news, trends & analysis

Types of Query Execution in LINQ

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Advertisers

Advertise with TechnologyAdvice on CodeGuru and our other developer-focused platforms.

  • Privacy Policy
  • California – Do Not Sell My Information

Property of TechnologyAdvice. © 2023 TechnologyAdvice. All Rights Reserved Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.

  • AI & ML
  • Hypersonics
  • JADC2 & Comms
  • IT/Networks
  • Information Warfare
  • Electronic Warfare
  • 3D Printing
  • The Compass
  • Events Calendar
  • Newsletters (Opens in new window)

5 strategies to speed adoption of AI and data analytics across the DOD

task net 4 5

Our world is digital. Every day more than 300 million terabytes of data are created, collected and stored. Imagine a stack of books that stretches from the Earth to the Moon and back, and then do that 40,000 times. That’s approximately how much data we’re talking about.

In navigating this digital landscape, the Department of Defense stands at the precipice of transformation. By embracing advanced technologies, fostering a culture of data accessibility and collaboration, and ensuring personnel have a fundamental grasp of machine learning, the DoD is poised to unlock the full potential of data analytics and artificial intelligence. In doing so, it will strengthen its ability to make well-informed decisions, adapt to evolving challenges and secure our nation’s defense in an increasingly data-driven world.

The immense amount of data at our fingertips presents both an opportunity and a challenge. Within the Naval Aviation Enterprise, technological advancements have given rise to sensors and information collection systems that produce an unprecedented volume of data. While this data surge holds great potential to better understands the battlespace, it has also created an “information overload” that is now straining the Sailors and Marines tasked with making sense of this data.

To meet this challenge head-on, the DoD must continue to leverage these five strategies:

1. Improve data collection . The DoD’s commitment to investing in advanced sensors and collection platforms that generate data more efficiently is paramount. These systems must be designed with open architectures and industry standards to ensure seamless interoperability and scalability.

2. Overcome data silos. Standardized protocols and a secure, trustworthy cloud infrastructure should enable comprehensive data sharing across organizations within the DoD. This accessibility is key to fostering multisource intelligence fusion, enhancing collaboration and bolstering trust in data-driven decisions.

3. Harness the power of data analytics. Data analytics, including both traditional and advanced data science methods, can provide valuable insights by uncovering trends, anomalies and correlations within the massive data sets. These analytics can help identify critical patterns and generate actionable intel in real-time.

4. Sift through the data deluge with automation, AI and ML, and a well-informed workforce. Automation, AI and ML can process, analyze and categorize data more rapidly, reducing the workload on operators. While competitively reaching out to experts in industry and academia as an extended part of our team is vital, DoD civilian and military personnel should also possess a general understanding of AI/ML concepts. This knowledge empowers them to make well-informed decisions on where and when to apply these technologies effectively.

5. Use collaborative frameworks . Collaboration is the linchpin of success, particularly as the DoD transitions to centralized processing sites. User-friendly, collaborative tools and visualization techniques facilitate data analysis and understanding among decision-makers, even when geographically dispersed.

With these strategies in play, the DoD continues to integrate AI/ML technologies into its operations. A foundational aspect of this transformation is the development of a more coherent approach to AI and data, with an emphasis on aligning initiatives with dependable and pertinent data sources. Notably, the Naval Air Systems Command and its associated program offices stand at the forefront of these efforts.

NAVAIR is teaming with U.S. Naval Surface Force’s Task Force Hopper to explore fielding of AI-embedded sensors onto aircraft, exemplifying a collaborative framework approach across the Navy. This endeavor encompasses the deployment of a robust data architecture that seamlessly integrates sensor data. Additionally, it equips naval personnel with specialized AI and ML tools to manage the substantial volumes of data generated daily by both naval ships and aerial assets.

The growing imperative for AI-enabled naval systems to effectively counter evolving radio frequency threats has propelled cognitive electromagnetic warfare. At the forefront of this transformative landscape, the Airborne Electronic Attack Systems Program Office is pioneering groundbreaking developments.

The development of ML models tailored for the EA-18G Growler airborne electronic attack suite allows precise RF signal classification and fortifies EW capabilities in the face of agile, adaptive and potentially adversarial radar systems.

Another example of AI in action, the Unmanned Carrier Aviation Program Office is making significant progress with advanced autonomous air-to-air refueling. This cutting-edge endeavor aims to empower aerial systems with the capacity to acquire knowledge and adapt seamlessly to diverse unmanned aerial vehicles seeking safe aerial refueling, ultimately making fully autonomous refueling possible.

In order to ensure the workforce comprehensively embraces these technological advancements, NAVAIR offers a training program on the fundamentals and practical applications of AI, ML and deep learning. This course equips the workforce to adeptly oversee AI/ML projects and effectively engage with industry and academia experts who play pivotal roles in advancing AI on aircraft and other systems for the DoD.

The DoD has begun a transformative journey into the digital landscape, where data analytics and AI will shape the future of national defense. As it strategically integrates these technologies across its organization, the DoD will not only adapt to the data-driven world but thrive in it, safeguarding America and its allies for years to come.

Cmdr. Justin Letwinsky is the assistant program manager for systems and engineering for electronic warfare, and chief military advisor for AI/ML for Naval Air Systems Command. He is a MH-60 pilot with almost 20 years of experience as a naval officer. The views expressed are those of the author and do not necessarily reflect the views of Department of Defense or Department of the Navy.

More In Opinion

task net 4 5

Meet the Navy’s first robotics warfare specialist

Master chief robotics warfare specialist christopher rambert was pinned less than a week after the service unveiled the new robotics-focused rating..

task net 4 5

Missile warning payload delay could push back 2025 launch plans

The late payload is being developed by rtx and will be integrated onto a lockheed martin satellite..

task net 4 5

Space Futures Command could begin limited operations this year

Chief of space operations gen. chance saltzman announced the creation of the command feb. 12 as part of a slate of organizational changes..

task net 4 5

Germany buys Rheinmetall’s Skyranger to reinstate mobile air defenses

Mounted on boxer vehicles, the weapons are meant to close a capability left by the 2010 retirement of germany's gepard air-defense tanks..

task net 4 5

France orders 3,000 camouflage nets for cloaking foxhole radio signals

Detection by way of electromagnetic emissions is a constant danger faced by ukrainian forces in their defense against russian invaders, analysts have said., featured video, military issues on capitol hill, and black sea updates | defense news weekly full episode, 2.24.24.

task net 4 5

How do I create a basic monthly budget? — Money Minute

task net 4 5

Navy’s newest aircraft carrier recoups after long mission

task net 4 5

NATO’s naval front line

Trending now, space force’s fixed-price push includes some exceptions, calvelli says, ukraine claims to down another russian early warning and control plane, here are the winners and losers in us army’s force structure change, us space force to launch more integrated units to boost efficiency.

Wife of ex-Red Sox pitcher Tim Wakefield dies of cancer, less than 5 months after husband

task net 4 5

The wife of former Boston Red Sox pitcher Tim Wakefield died on Wednesday, the team announced in a statement on behalf of the Wakefield family.

Stacy Wakefield died of pancreatic cancer at her home in Massachusetts, less than five months after her husband passed away from brain cancer. Tim Wakefield was 57.

"The loss is unimaginable, especially in the wake of losing Tim just under five months ago. Our hearts are beyond broken. We will remember Stacy as a strong, loving, thoughtful and kind person, who was as down-to-earth as they come," the family said in a statement.

"We feel so lucky to have had her in our lives, and we take comfort in the fact that she will be reunited with Tim, the love of her life. We would like to thank all of Stacy’s doctors, nurses and caretakers who helped her from diagnosis to today."

"We are eternally grateful for your unmatched care and support. And to all of you who have sent well wishes over these last several months, we truly appreciate your kindness. We kindly ask for privacy at this time as we try to process this profound loss.”

All things Red Sox: Latest Boston Red Sox news, schedule, roster, stats, injury updates and more.

Wakefield is survived by children Trevor and Brianna.

Reimagining the nursing workload: Finding time to close the workforce gap

US healthcare organizations continue to grapple with the impacts of the nursing shortage—scaling back of health services, increasing staff burnout and mental-health challenges, and rising labor costs. While several health systems have had some success in rebuilding their nursing workforces   in recent months, estimates still suggest a potential shortage of 200,000 to 450,000 nurses in the United States, with acute-care settings likely to be most affected. 1 Gretchen Berlin, Meredith Lapointe, Mhoire Murphy, and Joanna Wexler, “ Assessing the lingering impact of COVID-19 on the nursing workforce ,” McKinsey, May 11, 2022. Identifying opportunities to close this gap remains a priority in the healthcare industry. This article highlights research conducted by McKinsey in collaboration with the ANA Enterprise on how nurses are actually spending their time during their shifts and how they would ideally distribute their time if given the chance. The research findings underpin insights that can help organizations identify new approaches to address the nursing shortage and create more sustainable and meaningful careers for nurses.

Over the past three years, McKinsey has been reporting on trends within the nursing workforce , collecting longitudinal data on nurses’ self-reported likelihood to leave their jobs and factors driving nurses’ intent to leave. 2 “ Nursing in 2023: How hospitals are confronting shortages ,” McKinsey, May 5, 2023. As of March 2023, 45 percent of inpatient nurses (who make up about 2.0 million of the 4.2 million nurses in the United States 3 Nursing fact sheet, American Association of Colleges of Nursing, updated September 2022. ) reported they are likely to leave their role in the next six months. Among those who reported an intent to leave, the top two reasons cited were not feeling valued by their organization and not having a manageable workload. In fact, nurses have consistently reported increasing workload burden as a main factor behind their intent to leave.

About the research

We conducted a survey of 310 registered nurses across the United States from February 8 to March 22, 2023. Our goal was to understand nurses’ perception of time spent throughout the course of a shift and to identify existing and desired resources to help nurses provide high-quality care. Our sample focused on nurses in roles that predominantly provide direct patient care in the intensive-care unit, step-down, general medical surgical, or emergency department settings. Insights were weighted by length of shift (the minimum shift time included was six hours).

For questions related to intent to leave nursing, all nurses from any care setting (including home care and long-term care facilities) were included. Our survey questions on intent to leave have been kept consistent to collect longitudinal data on nurses’ intent. Our last survey, of 368 frontline direct-care nurses, was conducted in September 2022.

In our new survey, nurses provided a breakdown of the average time spent during a typical shift across 69 activities (see sidebar “About the research”). They also reported their views on the ideal amount of time they would like to spend on these same activities. In looking at ways to redesign care activities, we found the potential to free up to 15 percent of nurses’ time through tech enablement, or automation, and improved delegation of tasks (Exhibit 1). Leveraging delegation and tech enablement could reduce and redistribute activities that nurses report being predominantly responsible for. The subsequent reduction in time savings could improve nursing workload and their ability to manage more complex patients. When we translate the net amount of time freed up to the projected amount of nursing time needed, we estimate the potential to close the workforce gap by up to 300,000 nurses.

Nurses report a desire to spend more time with their patients, coach fellow nurses, and participate in professional-growth activities

In our survey, we explored where nurses wanted to spend more of their time (Exhibit 2). The responses fall into the following three categories.

Direct patient care

Nurses report spending the majority of their shift—54 percent, or about seven hours of a 12-hour shift—providing direct patient care and creating personal connections with patients (direct patient care includes patient education, medication administration, and support of daily-living activities). The survey reveals that nurses wish to spend even more time in these activities.

Spending sufficient time on patient-care activities promotes both nursing satisfaction and quality of patient care. 4 Terry L. Jones, Patti Hamilton, and Nicole Murry, “Unfinished nursing care, missed care, and implicitly rationed care: State of the science review,” International Journal of Nursing Studies , June 2015, Volume 52, Issue 6. Furthermore, rushing care and not having sufficient time to meet patients’ needs can contribute to moral distress and burnout.

Teaching and training for new nurses and peers

Nurses report spending on average about 2 percent of their shift teaching peers and students (excluding shifts when nurses are in a dedicated teaching or “precepting” role), an activity they say they want to spend double the amount of time on. Peer-to-peer teaching is an important component of building workplace cohesiveness, improving patient outcomes, and preparing new generations of nurses. In our survey, nurses report that they often lack the time to engage in coaching new nurses. As a result, important informal teaching, which is critical to build confidence and to support skill development for newer nurses, is often missed.

Involvement in professional-growth activities

Similar to educating other nurses, nurses report wanting to spend more than double the amount of time on growth and development activities (about 7 percent of an ideal shift). These activities include participating in shared governance, reviewing and reading work emails, and completing annual requirements and continuing education hours.

Freeing up nursing time to support organizational initiatives and further professional development may contribute to a nursing staff that is more engaged, feels valued, and has a strong connection to their departments.

Nurses desire to spend less time on documentation, hunting and gathering, and administrative and support tasks

Charting and documentation.

Documentation continues to greatly contribute to nurses’ workloads, making up 15 percent of a nurse’s shift. The most time-consuming documentation tasks are head-to-toe assessments, admissions intakes, and vitals charting, which account for the majority of documenting time (70 percent). Nurses say that ideally, documenting should make up only about 13 percent of their shift. But without realistic and effective alternatives (for example, nursing scribes, device integration, reduction in documentation requirements, and AI to aid with documentation), it is unlikely that nurses’ documentation burden can be fully alleviated.

Hunting and gathering

For nurses, hunting and gathering means searching for individuals, equipment, supplies, medications, or information. Nurses report that they spend about 6 percent of a 12-hour shift on hunting and gathering—tasks they would spend approximately 3 percent of their shift on in an ideal shift.

Activities best delegated to support staff

Nurses report spending nearly 5 percent of their shift on tasks that do not use the fullest extent of their license and training. For example, they say they spend nearly an hour on nutrition and daily-living activities, such as toileting, bathing, and providing meals and water. In an ideal shift, nurses say they would spend about 3 percent of their time on these activities.

Redesigning care models: Adjusting how nurses spend their time

As we consider how to alleviate nursing workforce challenges, one area of intervention could be evaluating how current care models can be redesigned to better align nursing time to what has the most impact on patient care. Performing below-top-of-license or non-value-adding activities can create inefficiencies that lead to higher healthcare costs and nurse dissatisfaction. Rigorously evaluating whether tasks can be improved with technology or delegated to allow nurses to spend time on activities they find more valuable could help to reduce the time pressures felt by nurses. 5 “National guidelines for nursing delegation,” a joint statement by the NCSBN and American Nurses Association, April 1, 2019. In our analysis, we reviewed the activities nurses say they would ideally spend less time on and considered whether delegation and tech enablement of such tasks could free up nurses’ time.

Based on our analysis, we estimate that full or partial delegation of activities to roles including technicians, nursing assistants, patient-care technicians, food services, ancillary services, and other support staff, could reduce net nursing time by 5 to 10 percent during a 12-hour shift (Exhibit 3).

While nurses report wanting to spend more time overall on direct patient care, there are specific tasks that could be delegated both vertically and horizontally to ensure that the work nurses perform is at the top of their license and promotes professional satisfaction. Appropriate delegation requires training support staff and upskilling where appropriate, as well as evaluating systemwide resources that can be used where needed. For example, within direct patient care, nearly an hour could potentially be freed up by delegating tasks such as patient ambulation, drawing labs and starting IVs, transferring patients, and supporting patient procedures.

Full or partial delegation of activities to roles such as technicians and other support staff could reduce net nursing time by 5 to 10 percent during a 12-hour shift.

Tasks that are evaluated for redistribution to other clinical and non-clinical staff can also be considered as part of broader care-model redesign. Upskilling support staff across clinical and nonclinical roles can often result in overall better use of resources already in place across a health system.

Tech enablement

Based on our assessment, we estimate that a net 10 to 20 percent of time spent during a 12-hour shift is spent on activities that could be optimized through tech enablement. Investing in digital approaches that automate tasks (either completely or partially), rather than simply redistributing workload, could potentially free up valuable time for nurses (Exhibit 4).

Examples of tech enablement and delegation in practice

To determine the amount of time that could potentially be freed up over the course of a nurse’s shift, we used estimations based on best-in-class care delivery models from practice, innovative emerging technology from industry, and how easy it would be for health systems to implement the intervention (for example, cost and technological requirements).

Tech-enablement

  • Robotic automatic-guided vehicles (AGVs) deliver equipment, food, and supplies throughout a hospital. 1 “Robots help nurses get the job done–with smiles and beeps,” Cedars Sinai, November 29, 2021.
  • Robotic pill-picker machines select and deliver medicines throughout a hospital. 2 Jay Kiew, “The digital surgery: Humber River Hospital reinvents itself with AI & robotics,” Change Leadership, June 16, 2018.
  • Virtual nurses monitor patients remotely, working alongside a bedside-care team comprising a bedside RN, bedside licensed vocational nurse, and virtual RN. 3 Giles Bruce, “Trinity Health plans to institute virtual nurses across its 88 hospitals in 26 states,” Becker’s Health IT, January 13, 2023.
  • Ambient intelligence (that is, passive, contactless sensors embedded in a clinical setting to recognize movement or speech) reduces documentation workload and can continuously monitor patients. 4 Albert Haque, Arnold Milstein, and Li Fei-Fei, “Illuminating the dark spaces of healthcare with ambient intelligence,” Nature , September 9, 2020.
  • Centralized training for roles such as transporters that can then be utilized in all areas of the hospital.
  • Upskilling employees and modifying staffing models allow nurses to work in units where they are needed most (for example, non-critical-care nurses in critical-care departments).

For example, nurses spend 3 percent of their shifts on patient turning and repositioning. This task could be optimized through innovative “smart” hospital-bed technology, including bed-exit alarms, advanced therapy for redistributing pressure, integrated scales and measurements, and remote information on patient conditions. Voice-automated devices and smart beds can also equip patients with control and autonomy over their rooms and preferences (for example, shades, television, and lighting) without nurse intervention (see sidebar “Examples of tech enablement and delegation in practice”).

These interventions, however, can be costly and may not be appropriate solutions in every system. Healthcare organizations will need to assess the specific needs of nurses and patients to determine which interventions will have the most impact.

Healthcare organizations could also consider continuously evaluating the digital approaches they have implemented to ensure that the technology itself does not create redundancies or rework, introduce delays, or adversely increase workload. For example, 37 percent of nurses report that they do not have access to vital signs or telemetry machines that are integrated with electronic medical records for automatic documentation. This could explain why nurses say they could spend less time—about 30 percent less—documenting vital signs. Technology like scanners and automated vitals machines have been an effective way to streamline documentation. But nurses still report spending nearly 10 percent of their shift scanning medications into the patient record, documenting vitals and completed patient education, and drafting progress notes.

Nurse time saved through care-model changes and innovations can benefit patients and nurses—and contribute to building sustainable careers in healthcare

The impact of care-model redesign could range from improving workload sustainability to addressing a substantial portion of the projected 200,000 to 450,000 nursing gap. Our analysis finds a potential net time savings of 15 to 30 percent of a 12-hour shift, based on estimating the possible range of time reduced through delegation 6 “ANAs principles for delegation,” American Nurses Association, 2012. or tech enablement. 7 Mari Kangasniemi, Suyen Karki, Noriyo Colley, and Ari Voutilainen, “The use of robots and other automated devices in nurses' work: An integrative review,” International Journal of Nursing Practice , August 2019, Volume 25, Issue 4.

In our conservative estimate, there would be no additional opportunity to alleviate the potential nursing shortage, as health systems would reallocate the saved time to their current nursing staff for activities they say they would spend more time on, including time with patients, teaching peers, and investing in their growth and development (Exhibit 5). However, this reallocation of time could improve the sustainability of nursing careers in acute-care practice.

In our optimistic estimate, after reallocating time back to nurses, health systems could free up a 15 percent net time savings, which could translate to closing the nursing workforce gap by up to 300,000 inpatient nurses. Achieving this may require health systems to invest heavily in technology, change management, and workflow redesign.

Realizing these changes will require bold departures from healthcare organizations’ current state of processes. It will be critical for hospitals to bring both discipline and creativity to redesigning care delivery in order to effectively scale change and see meaningful time savings. Close collaboration beyond nursing is also paramount to ensure alignment across the care team and hospital functions including administration, IT, informatics, facilities, and operations. A comprehensive evaluation of redesign requirements can enable health systems to understand what is limiting care-model change (for example, policies, skill development, education). Investment in education and additional onboarding may be needed to upskill and train staff on expectations as work is shifted across roles. Partnering with tech companies and industry vendors in areas such as electronic-health-record platforms can accelerate innovation and implementation to build off existing tools and reduce implementation risks. Although the idea of change may be daunting, incorporating innovations in healthcare delivery could be a strategy for building a sustainable workload that could attract and retain nursing talent by allowing them to do more of what matters to them most: taking care of patients and one another.

Gretchen Berlin, RN , is a senior partner in McKinsey’s Washington, DC, office; Ani Bilazarian, RN , is a consultant in the New York office; Joyce Chang, RN , is an associate partner in the Bay Area office; and Stephanie Hammer, RN , is a consultant in the Denver office.

The authors wish to thank Katie Boston-Leary, RN, and the ANA Enterprise for their contributions to this article. The authors also wish to acknowledge and thank the entire healthcare workforce, including all of those on the front line.

Explore a career with us

Related articles.

Two female surgeons confer before seeing patients in the hospital

Nursing in 2023: How hospitals are confronting shortages

Surgeon tying surgical mask

Surveyed nurses consider leaving direct patient care at elevated rates

Smiling female nurse.

Nurses and the Great Attrition

task net 4 5

task net 4 5

Learn about API Management from experts on today’s innovative API architectures to accelerate growth, improve discoverability, transform existing services, and more! All with a hybrid, multi-cloud management platform for APIs across all environments.

Async in 4.5: Enabling Progress and Cancellation in Async APIs

' data-src=

Brandon Bray

June 6th, 2012 3 3

The apps developers want to develop today are fast and fluid and the async features in .NET make this easier than ever. The world is also highly connected now which makes waiting for data a real concern for building great customer experiences. Alok Shriram from the .NET Base Class Library program management team continues his discussion on the async programming model by showing how to achieve both fast-and-fluid and connected scenarios. – Brandon

In this post, we will look at how you can enable your users to interact with async tasks, introduced in the Task Parallel Library (TPL), specifically by adding progress bars and cancellation buttons to your apps. It builds on an earlier post about the async programming model in the .NET Framework 4.5.

User experience and async

As a developer, you want to provide your users with great UI experiences in the apps that you build. You strive to produce visually compelling apps that are intuitive and that enable the completion of your users’ goals. It’s equally important that you provide feedback on progress and let users opt out of a lengthy operation. Progress bars and cancel buttons are the accepted and expected norm in apps today (and have been, for the last 20 years!).

The async programming model in the .NET Framework 4.5 provides an innovative new pattern for doing work in the background. The pattern is highly productive and solves common developer challenges. In many cases, you’ll want to choose async to ensure that your app is very responsive to users. For example, if you have a photo app, you might use the async pattern to load images from either a disk or a web service when you’re populating a photo gallery. While the images will likely load quickly, users understand that the pictures may load in an arbitrary order. As a result, exposing extra UI for monitoring or canceling the operation doesn’t make sense, and would only add noise to your app experience.

If a user-requested operation is expected to take a long time in your app, you’ll want to expose UI that enables the user to follow the progress and interact with the operation. Note that progress monitoring and cancellation aren’t new with the async pattern, but they’re important considerations when you adopt the async programming model. Just because you’re using the async pattern doesn’t mean that you won’t keep the user waiting! For example, your photo app may include a button that provides your users with the full list of EXIF tags used in their potentially very large photo collections. Since you cannot predict how long this operation will take, it makes sense to add UI for progress and cancellation. This is the scenario that we will discuss in this post.

sample_progress_dialog

Figure: Sample progress dialog box, with a cancel button

Enabling progress bars with async

We are all familiar with hourglasses and progress bars, and how they help users better understand what an app is doing. You’ll want to inform users that there will be a wait, provide a sense of how long the wait might be, and enable them to interact with the app during the wait. The progress and cancellation features of the async programming model enable you to deliver on all these needs.

At a high level, an app spawns off a task, and needs the task to report progress back to the app, enabling the app to present that information to the user. At a low level, the task has to understand the scope of work that it needs to accomplish, and then assess its progress on that work at relatively frequent intervals. For example, reporting progress twice while working on 100 items won’t enable a fluid user experience. For a better experience, you’d probably start with reporting progress once per item, and then change that as needed.

We introduced the IProgress<T> interface to enable you to create an experience for displaying progress. This interface exposes a Report(T) method, which the async task calls to report progress. You expose this interface in the signature of the async method, and the caller must provide an object that implements this interface. Together, the task and the caller create a very useful linkage (and could be running on different threads).

We also provided the Progress<T> class, which is an implementation of IProgress<T>. You are encouraged to use Progress<T> in your implementation, because it handles all the bookkeeping around saving and restoring the synchronization context. Progress<T> exposes both an event and an Action<T> callback, which are called when the task reports progress. This pattern enables you to write code that simply reacts to progress changes as they occur. Together, IProgress<T> and Progress<T> provide an easy way to pass progress information from a background task to the UI thread.

Async progress example

Let’s consider what it takes to build an async API that can report back progress. A simple use case for this would be an API that accepts a list of images, does some processing on them, and then uploads them to a web service. The signature of the method would look like this:

async Task< int > UploadPicturesAsync(List<Image> imageList, IProgress< int > progress)

Let’s implement this async method. We’ll focus specifically on the code that calculates and reports progress back to the UI thread:

async Task< int > UploadPicturesAsync(List<Image> imageList, IProgress< int > progress) { int totalCount = imageList.Count; int processCount = await Task.Run< int >(() => { int tempCount = 0; foreach (var image in imageList) { //await the processing and uploading logic here int processed = await UploadAndProcessAsync(image); if (progress != null ) { progress.Report((tempCount * 100 / totalCount)); } tempCount++; } return tempCount; }); return processCount; }

Note that we used int as the generic T parameter in this example. int lends itself to a very simple implementation that covers many scenarios. Alternatively, you may find that you need to use one of your own types that encapsulates more information, such as both the progress and the entire scope of the work.

One of the biggest concerns you’ll have to address from the perspective of user experience is how frequently you report back progress. In this example, we are reporting back progress for every image that is processed and uploaded, which gives the user a sense that the operation is moving forward. However, if each iteration of this loop took a really long time (say, on the order of minutes), we would have to come up with a finer-grained way of reporting progress. On the other hand, if each iteration took milliseconds (think copying 1000 bytes from memory to disk), we might be able to make our progress reporting interval coarser-grained without sacrificing the responsive user experience.

On the consuming side of this API, on the UI thread, we first need to define an event handler Action<T>, which will be called when IProgress<T>.Report is invoked. The code for this is shown below.

void ReportProgress( int value ) { //Update the UI to reflect the progress value that is passed back. }

Next we need to set up our Progress<T> instance and invoke the async method, which is triggered by a button click event in this example:

Now we have an async task that reports progress back to the UI thread, enabling a good user experience. You can build on this code to create something more sophisticated, but the principles will remain the same.

Canceling async tasks

Cancellation is another aspect of user interaction that you need to consider to build compelling user experiences. The cancel button shown in the progress dialog box illustrated earlier is as iconic as the progress bar.

In the Task Parallel Library (TPL), cancellation is not strongly tied to a cancel button, although that is one of the ways in which it frequently manifests itself in a UI. Cancellation can also be used in situations where we want to time out long-running tasks or cancel parallel tasks.

Cancellation is controlled by the CancellationToken structure. You expose cancellation tokens in the signature of cancelable async methods, enabling them to be shared between the task and caller. In the most common case, cancellation follows this flow:

  • The caller creates a CancellationTokenSource object.
  • The caller calls a cancelable async API, and passes the CancellationToken from the CancellationTokenSource (CancellationTokenSource.Token).
  • The caller requests cancellation using the CancellationTokenSource object (CancellationTokenSource.Cancel()).
  • The task acknowledges the cancellation and cancels itself, typically using the CancellationToken.ThrowIfCancellationRequested method.

As part of supporting the task-based async programming model in the .NET Framework 4.5, we added the CancellationToken structure to the signatures of a large set of async APIs in the .NET Framework. For example, the HttpClient class exposes a GetAsync method overload that accepts a cancellation token. However, it is not essential for all async methods to support cancellation. For instance, if you look at the HttpContent class, the LoadIntoBufferAsync method does not expose an overload with a cancellation token.

You should consider using cancellation for all methods that may take a long time to complete. While evaluating the execution time of an API, you should consider the worst-case scenario to inform your decision.

Async cancellation example

Now that we’ve discussed how cancellation works, let’s write some code to consume a cancelable async API. Let’s extend our photo upload API by adding an overload that takes a cancellation token. The API signature now looks like the following:

async Task< int > UploadPicturesAsync(List<Image> imageList, IProgress< int > progress, CancellationToken ct)

To consume this API, we write the following code in the UI button click event handler:

In order to cancel the UploadPicturesAsync task, we’ll add the following line of code to the cancel button click handler:

cts.Cancel();

This call will signal the token that was passed to UploadPicturesAsync that it has been canceled, and will request the task to be canceled. When consuming an async API that supports cancellation, you should ensure that you wrap the call to that method in a try/catch block, to catch any OperationCancelledException(OCE) exceptions that are thrown. If you don’t, an unhandled OCE could cause your app to fail.

If UploadPicturesAsync were a .NET Framework class library method, this is all you would need to worry about — the .NET Framework would take care of the mechanics of cancellation. However, if you’re implementing the UploadPicturesAsync method yourself, you would have to make sure that the cancellation token was handled appropriately. Let’s take a peek inside this method to see what is happening.

async Task< int > UploadPicturesAsync(List<Image> imageList, IProgress< int > progress, CancellationToken ct) { int processCount = await Task.Run< int >(() => { foreach (var image in imageList) { //await UploadAndProcessAsync (this is another method in the app) bool success = await UploadAndProcessAsync(image) ct.ThrowIfCancellationRequested(); // progress logic here } },ct); return processCount;

As you can see, the mechanics of detecting and reacting to a cancellation token are quite simple. You do, however, need to ensure that your data is always left in a consistent state. For example, if the operation in our example is canceled halfway through an upload, we might have only some of the images uploaded. You would have to decide if that was OK.

Note: When you use the Task.Run with a delegate that supports cancellation, make sure to pass the cancellation token as a parameter to Task.Run, in addition to passing it to the lambda expression that you are constructing. Failure to do so will result in a cancellation operation on the lambda resulting in the task terminating in a faulted state.

As with progress polling, you’ll also need to decide how frequently you will check for the cancellation state. You should check frequently enough to ensure that the user experience is seamless, but make sure that the checking does not slow down the operation.

The task-based async model is a powerful new innovation in the .NET Framework 4.5, as we discussed in our earlier post . It enables you to build applications that are both responsive and scalable. However, your applications should continue to provide user experiences that align with common expectations. The async programming model enables you to deliver on those expectations by providing patterns for cancellation and progress monitoring. These patterns are easy to adopt and require minimal changes to existing code.

The Visual Studio Asynchronous Programming site on MSDN is a great resource for samples, whitepapers and talks on the new language features and support. MSDN also has a great topic discussing best practices for progress and cancellation UI in apps. You should also check out the Parallel Programming with .NET blog for a more in-depth discussion of parallel programming.

' data-src=

Comments are closed. Login to edit/delete your existing comments

' data-src=

Love the exemplary souce code here. Edge&Chrome display it in mixed with html form 🙂   

' data-src=

I also love the code and examples. Funny how two readers comment some 7 years after, and then only a month apart. The code shows up fine in Firefox…  🙂

' data-src=

According to proper usage async/await in implementation UploadPicturesAsync (see Stephen Cleary https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html ) You should not use Task.Run in implementation e.g.

light-theme-icon

The Earthquake Event Page application supports most recent browsers, view supported browsers . Or, try our Real-time Notifications, Feeds, and Web Services .

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Task<TResult> Class

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Represents an asynchronous operation that can return a value.

Type Parameters

The type of the result produced by this Task<TResult> .

The Task<TResult> class represents a single operation that returns a value and that usually executes asynchronously. Task<TResult> objects are one of the central components of the task-based asynchronous pattern first introduced in the .NET Framework 4. Because the work performed by a Task<TResult> object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the Status property, as well as the IsCanceled , IsCompleted , and IsFaulted properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform.

Task<TResult> instances may be created in a variety of ways. The most common approach, which is available starting with the .NET Framework 4.5, is to call the static Task.Run<TResult>(Func<TResult>) or Task.Run<TResult>(Func<TResult>, CancellationToken) method. These methods provide a simple way to start a task by using default values and without acquiring additional parameters. The following example uses the Task.Run<TResult>(Func<TResult>) method to start a task that loops and then displays the number of loop iterations:

An alternative, and the most common way to start a task in the .NET Framework 4, is to call the static TaskFactory.StartNew or TaskFactory<TResult>.StartNew method. The Task.Factory property returns a TaskFactory object, and the Task<TResult>.Factory property returns a TaskFactory<TResult> object. Overloads of their StartNew method let you pass arguments, define task creation options, and specify a task scheduler. The following example uses the TaskFactory<TResult>.StartNew(Func<TResult>) method to start a task. It is functionally equivalent to the code in the previous example.

For more complete examples, see Task-based Asynchronous Programming .

The Task<TResult> class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the Task.Run and Task.Factory.StartNew methods are the preferred mechanisms for creating and scheduling computational tasks, but for scenarios where task creation and scheduling must be separated, the constructors may be used, and the task's Start method may then be used to schedule the task for execution at a later time.

Starting with desktop apps that target the .NET Framework 4.6, the culture of the thread that creates and invokes a task becomes part of the thread's context. That is, regardless of the current culture of the thread on which the task executes, the current culture of the task is the culture of the calling thread. For apps that target versions of the .NET Framework prior to the .NET Framework 4.6, the culture of the task is the culture of the thread on which the task executes. For more information, see the "Culture and task-based asynchronous operations" section in the CultureInfo topic. Note that Store apps follow the Windows Runtime in setting and getting the default culture.

For operations that do not return a value, you use the Task class. Starting with C# 7.0, for a more lightweight task that is a value type rather than a reference type, use the System.Threading.Tasks.ValueTask<TResult> structure.

Constructors

Explicit interface implementations, extension methods, thread safety.

All members of Task<TResult> , except for Dispose() , are thread-safe and may be used from multiple threads concurrently.

  • Task Parallel Library (TPL)
  • Task-based Asynchronous Programming
  • Samples for Parallel Programming with the .NET Core and .NET Standard

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

MiMedx: Q4 Earnings Snapshot

MARIETTA, Ga. — MARIETTA, Ga. — MiMedx Group Inc. (MDXG) on Wednesday reported fourth-quarter net income of $47 million.

On a per-share basis, the Marietta, Georgia-based company said it had net income of 32 cents. Earnings, adjusted for non-recurring gains and to account for discontinued operations, were 4 cents per share.

The results did not meet Wall Street expectations. The average estimate of three analysts surveyed by Zacks Investment Research was for earnings of 8 cents per share.

The developer of biomaterials made from sterilized human amniotic membrane posted revenue of $86.8 million in the period, which beat Street forecasts. Three analysts surveyed by Zacks expected $85.6 million.

For the year, the company reported profit of $46.6 million, or 37 cents per share. Revenue was reported as $321.5 million.

This story was generated by Automated Insights (http://automatedinsights.com/ap) using data from Zacks Investment Research. Access a Zacks stock report on MDXG at https://www.zacks.com/ap/MDXG

task net 4 5

Feature summary | Photoshop desktop (February 2024 release)

Learn about new features and enhancements in the February 2024 version (version 25.5) release of Photoshop desktop.

Update the app Try out the latest features and enhancements in the Photoshop app for general availability.

Create your own Adjustment Presets to export and share with others

Create and save  Adjustment Presets that reflect your personal style.

You can also share these with others or leverage other people's Adjustment Presets to apply to your images in Photoshop. 

To learn how to create and save your Adjustment Presets, as well as export or import them,  check out Adjustment, Fill layers, and Presets .

Access more text editing capabilities from the Contextual Task Bar

Make your text-editing workflows more intuitive and streamlined with the text editing capabilities in the new menu options of the Contextual Task Bar .  

You can now adjust text alignment, spacing (leading and kerning), and font style (bolding, italicizing, underlining) directly from the Contextual Task Bar .

Access more text editing capabilities from the Contextual Task Bar

To learn how to quickly access relevant tools and actions based on your current selection or context in your document, check out Contextual Task Bar in Photoshop .

Get help faster and easier

 alt=

Quick links

Legal Notices    |    Online Privacy Policy

Share this page

Language Navigation

task net 4 5

IMAGES

  1. Top 7 Features of ASP.Net 4.5 You Must Know

    task net 4 5

  2. Microsoft .Net Framework 4.5 Architecture

    task net 4 5

  3. New features and enhancements in .Net Framework 4.5

    task net 4 5

  4. .NET Framework 4.5 Descargar el instalador independiente completo

    task net 4 5

  5. MS .NET Framework Basic

    task net 4 5

  6. Microsoft .NET Framework 4.5

    task net 4 5

VIDEO

  1. Microsoft fixed my biggest complaint with Minimal APIs in .NET 7

  2. ASP.NET 4.5 Smart Tasks

  3. The Awesome New Queue of .NET 6 That You Skipped

  4. What's new in ASP.net 4.5 WebForms

  5. ASP.NET 4.5 Expert Skills Lesson 7-16: Use the TreeView and SiteMapDataSource controls

  6. ASP.NET 4.5 Expert Skills Lesson 7-15: Use the SiteMapPath control

COMMENTS

  1. Using Asynchronous Methods in ASP.NET 4.5

    The async keyword represents a hint that you can use to mark methods as task-based asynchronous methods. The combination of await, async, and the Task object makes it much easier for you to write asynchronous code in .NET 4.5. The new model for asynchronous methods is called the Task-based Asynchronous Pattern ( TAP ).

  2. Task Exception Handling in .NET 4.5

    In .NET 4.5, Tasks have significantly more prominence than they did in .NET 4, as they're baked in to the C# and Visual Basic languages as part of the new async features supported by the languages. This in effect moves Tasks out of the domain of experienced developers into the realm of everyone. As a result, it also leads to a new set of ...

  3. Using Task with .Net 4.0 vs .Net 4.5?

    output is different with .Net version 4.0 and 4.5. With 4.0 number 5 is repeated I can see the reason value of i is moved to 5 before some of the Tasks executed but same code with 4.5 shows different output. Called 0 Called 1 Enters 1 Working 1 Called 2 Called 3 Called 4 Finished Enters 0 Done 1 Enters 5 Working 0 Working 5 Done 0 **Enters 5 ...

  4. The Task Asynchronous Programming (TAP) model with async and await

    When the async method eventually completes its work, the task is marked as completed and the result, if any, is stored in the task. API async methods. You might be wondering where to find methods such as GetStringAsync that support async programming. .NET Framework 4.5 or higher and .NET Core contain many members that work with async and await.

  5. Task-based asynchronous programming

    Show 15 more. The Task Parallel Library (TPL) is based on the concept of a task, which represents an asynchronous operation. In some ways, a task resembles a thread or ThreadPool work item but at a higher level of abstraction. The term task parallelism refers to one or more independent tasks running concurrently.

  6. New TaskCreationOptions and TaskContinuationOptions in .NET 4.5

    Astute users of the Task Parallel Library might have noticed three new options available across TaskCreationOptions and TaskContinuationOptions in .NET 4.5: DenyChildAttach, HideScheduler, and (on TaskContinuationOptions) LazyCancellation. I wanted to take a few minutes to share more about what these are and why we added them. DenyChildAttach.

  7. Improved Multi-Threading Support in .NET 4.5

    Here, we use the task WhenAll method to wait until all of the other tasks finish. The .NET 4.5 Task API adds several new methods that make it very convenient to compose and synchronize tasks. Summing Up. Don't be fooled: there is no magic here. Asynchronous programming is still difficult and complex. This simple example program ends up ...

  8. The .NET 4.5 async/await feature in Promise and Practice

    The .NET 4.5 async/await feature provides an opportunity for improving the scalability and performance of applications, particularly where tasks are more effectively done in parallel. The question is: do the scalability gains come at a cost of slowing individual methods? In this article Jon Smith investigates this issue by conducting a side-by-side evaluation of the standard synchronous ...

  9. The overhead of async/await in NET 4.5

    Support for the async and await contextual keywords is one of the most convenient new features in .NET 4.5. It's always been possible to write asynchronous code, of course, but async/await allows it to be written in a relatively straightforward manner which neatly expresses the intention of the code, and means that it isn't necessary to ...

  10. Async in 4.5: Worth the Await

    Before the .NET Framework 4.5 Beta, asynchronous APIs in the .NET Framework followed three patterns: The Asynchronous Programming Model (APM), which has the format BeginMethodName and EndMethodName. The Event based Asynchronous Pattern (EAP), which relies on assigning delegates to event handlers that will be invoked when an event is triggered.

  11. Working with Asynchronous Operations in ASP.NET 4.5 Web Forms

    Introduction. Asynchronously running code can improve the overall performance and responsiveness of your web application. In ASP.NET 4.5 web forms applications you can register asynchronous methods with the page framework. The ASP.NET page framework and .NET 4.5 asynchronous programming support then executes the operations in asynchronous fashion.

  12. How to run Background Tasks in ASP.NET

    .NET 4.5.2 introduces HostingEnvironment.QueueBackgroundWorkItem to help run background tasks in an asp.net app domain. The method registers the task with asp.net so that the runtime will know about it during recycles or app shutdowns, and it gives you a CancellationToken that will cancel whenever an event like this is triggered.

  13. How to Create an Asynchronous HTTP Handler in ASP.NET 4.5

    In ASP.NET 4.5 you can use the new async/await keywords and Tasks to achieve the same effect with simplified design. Under ASP.NET 4.5 you can create a class that inherits from the HttpTaskAsyncHandler class and then override certain methods (as discussed later in this article). NOTE:

  14. Task Class (System.Threading.Tasks)

    Creates a continuation that executes according to the specified continuation options and returns a value. Continue With<TResult> (Func<Task,TResult>, Task Scheduler) Creates a continuation that executes asynchronously when the target Task completes and returns a value. The continuation uses a specified scheduler.

  15. 5 strategies to speed adoption of AI and data analytics across the DOD

    A U.S. Navy EA-18G Growler aircraft attached to the Electronic Attack Squadron (VAQ) 138 "Yellowjackets", assigned to Carrier Task Force 70, Carrier Strike Group 5, flies next to a KC-135 Stratotanker assigned to the 506th Expeditionary Air Refueling Squadron over the Pacific Ocean while flying in support of Exercise Valiant Shield 22 (VS22), June 13, 2022.

  16. What's New For Parallelism in .NET 4.5

    .NET 4 and Visual Studio 2010 saw the introduction of a wide range of new support for parallelism: the Task Parallel Library (TPL), Parallel LINQ (PLINQ), new synchronization and coordination primitives and collections (e.g. ConcurrentDictionary), an improved ThreadPool for handling parallel workloads, new debugger windows, new concurrency visualizations, and more.

  17. Stacy Wakefield, widow of Red Sox pitcher Tim Wakefield, dies

    Stacy Wakefield, widow of former Red Sox pitcher Tim Wakefield, dies of cancer less than 5 months after husband passed away. Your inbox approves Rewatch the best ads Men's coaches poll Women's ...

  18. Solutions to close the nursing shortage gap

    When we translate the net amount of time freed up to the projected amount of nursing time needed, we estimate the potential to close the workforce gap by up to 300,000 nurses. ... Nurses report spending nearly 5 percent of their shift on tasks that do not use the fullest extent of their license and training. For example, they say they spend ...

  19. New Stadium Inclusion Task Force disbanded, Legislature Chairwoman says

    BUFFALO, N.Y. — 2 On Your Side has learned the New Stadium Inclusion Task Force is no more. Erie County Legislature Chairwoman April Baskin announced Tuesday afternoon that it has adjourned ...

  20. What's New in Excel (February 2024)

    Excel for Web. 1. Chart Data Task Pane. You can now use the data task pane to edit your chart's data on the web. The data task pane supports the following: Change a chart's source data range via range picker UI (mouse selection) Expose new web-first UI to determine how data series are displayed on the chart (including which axis they are ...

  21. Pokémon Go Tour 2024: all Research tasks

    Step 3 of 4 Diamond Version. Evolve 3 Pokémon: Shadow Scizor; Activate Roar of Time's Adventure Effect: Shadow Honchkrow; Complete all tasks in this step: Dialga Candy x3, Dialga Candy XL x1, Spiritomb; Pearl Version. Evolve 3 Pokémon: Shadow Pinsir; Activate Spacial Rend's Adventure Effect: Shadow Mismagius; Complete all tasks in this step: Palkia Candy x3, Palkia Candy XL x1, Spiritomb

  22. Async in 4.5: Enabling Progress and Cancellation in Async APIs

    The task acknowledges the cancellation and cancels itself, typically using the CancellationToken.ThrowIfCancellationRequested method. As part of supporting the task-based async programming model in the .NET Framework 4.5, we added the CancellationToken structure to the signatures of a large set of async APIs in the .NET Framework.

  23. USGS Earthquake Hazards Program

    The Earthquake Event Page application supports most recent browsers, view supported browsers.Or, try our Real-time Notifications, Feeds, and Web Services.Real-time Notifications, Feeds, and Web Services.

  24. What is the point of .NET 4.6's Task.CompletedTask?

    29. Task.CompletedTask property is important when you need to give a caller a dummy Task (that doesn't return a value/result) that's already completed. This might be necessary to fulfill an "interface" contract or testing purposes. Task.FromResult (data) also returns a dummy Task, but this time with data or a result.

  25. Task<TResult> Class (System.Threading.Tasks)

    Remarks. The Task<TResult> class represents a single operation that returns a value and that usually executes asynchronously. Task<TResult> objects are one of the central components of the task-based asynchronous pattern first introduced in the .NET Framework 4. Because the work performed by a Task<TResult> object typically executes asynchronously on a thread pool thread rather than ...

  26. MiMedx: Q4 Earnings Snapshot

    On a per-share basis, the Marietta, Georgia-based company said it had net income of 32 cents. Earnings, adjusted for non-recurring gains and to account for discontinued operations, were 4 cents ...

  27. Feature summary

    Make your text-editing workflows more intuitive and streamlined with the text editing capabilities in the new menu options of the Contextual Task Bar. You can now adjust text alignment, spacing (leading and kerning), and font style (bolding, italicizing, underlining) directly from the Contextual Task Bar.

  28. Run two async tasks in parallel and collect results in .NET 4.5

    I've been trying for a while to get something I thought would be simple working with .NET 4.5. I want to fire off two long running tasks at same time and collect the results in in the best C# 4.5 (RTM) way. The following works but I don't like it because: I want Sleep to be an async method so it can await other methods; It just looks clumsy ...

  29. Prime Video: Poacher

    Originally created in Malayalam (മലയാളം), Poacher is a spine-chilling crime thriller about a group of Indian Forest Service officers, NGO workers, police constables and Good Samaritans risk their lives trying to track down the biggest elephant ivory poachers in the history of India and bring them to justice.