Click here to Skip to main content
12,399,561 members (50,353 online)
Click here to Skip to main content

Tagged as

Stats

89.2K views
953 downloads
64 bookmarked
Posted

Async/Await Could Be Better

, 11 Apr 2012 CPOL
This article will explain how the async/await pair really works and why it could be better if real cooperative threading was used instead.
using System;
using System.Collections.Generic;
using System.Threading;

namespace Pfz.Threading.Cooperative
{
	public sealed class CooperativeJobManager:
		IDisposable
	{
		private readonly HashSet<CooperativeJob> _allTasks = new HashSet<CooperativeJob>();
		internal readonly Queue<CooperativeJob> _queuedTasks = new Queue<CooperativeJob>();
		internal bool _waiting;
		private bool _wasDisposed;

		public CooperativeJobManager()
		{
			// The real implementation uses my UnlimitedThreadPool class.
			// I removed such class in this version to give a smaller download
			// and make the right classes easier to find.
			var thread = new Thread(_RunAll);
			thread.Start();
		}
		public void Dispose()
		{
			lock(_queuedTasks)
			{
				_wasDisposed = true;

				if (_waiting)
					Monitor.Pulse(_queuedTasks);
			}
		}

		public bool WasDisposed
		{
			get
			{
				return _wasDisposed;
			}
		}

		private void _RunAll()
		{
			CooperativeJob task = null;
			//try
			//{
				while(true)
				{
					lock(_queuedTasks)
					{
						if (_queuedTasks.Count == 0)
						{
							if (task == null)
							{
								do
								{
									if (_wasDisposed && _allTasks.Count == 0)
										return;

									_waiting = true;
									Monitor.Wait(_queuedTasks);
								}
								while (_queuedTasks.Count == 0);
							}
						}
						else
						{
							if (task != null)
								_queuedTasks.Enqueue(task);
						}

						if (_queuedTasks.Count != 0)
						{
							_waiting = false;
							task = _queuedTasks.Dequeue();
						}
					}

					CooperativeJob._current = task;
					if (!task._Continue() || task._waiting)
						task = null;
				}
			//} will only work with real stacksavers.
			//finally
			//{
			//	CooperativeTask._current = null;
			//}
		}

		public CooperativeJob Run(Action action)
		{
			if (action == null)
				throw new ArgumentNullException("action");

			var result = new CooperativeJob(this);
			var stackSaver = new StackSaver(() => _Run(result, action));
			result._stackSaver = stackSaver;
			lock(_queuedTasks)
			{
				_allTasks.Add(result);
				_queuedTasks.Enqueue(result);

				if (_waiting)
					Monitor.Pulse(_queuedTasks);
			}

			return result;
		}
		private void _Run(CooperativeJob task, Action action)
		{
			try
			{
				CooperativeJob._current = task;
				action();
			}
			finally
			{
				CooperativeJob._current = null;

				lock(_allTasks)
					_allTasks.Remove(task);
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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

Share

About the Author

Paulo Zemek
Engineer Microsoft Corporation
United States United States
I started to program computers when I was 11 years old, as a hobbyist, programming in AMOS Basic and Blitz Basic for Amiga.
At 12 I had my first try with assembler, but it was too difficult at the time. Then, in the same year, I learned C and, after learning C, I was finally able to learn assembler (for Motorola 680x0).
Not sure, but probably between 12 and 13, I started to learn C++. I always programmed "in an object oriented way", but using function pointers instead of virtual methods.

At 15 I started to learn Pascal at school and to use Delphi. At 16 I started my first internship (using Delphi). At 18 I started to work professionally using C++ and since then I've developed my programming skills as a professional developer in C++ and C#, generally creating libraries that help other developers do their work easier, faster and with less errors.

Now I just started working as a Senior Software Engineer at Microsoft.

Want more info or simply want to contact me?
Take a look at: http://paulozemek.azurewebsites.net/
Or e-mail me at: paulozemek@outlook.com

Codeproject MVP 2012, 2015 & 2016
Microsoft MVP 2013-2014 (now I work at Microsoft so I can't be a Microsoft MVP anymore)

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160721.1 | Last Updated 11 Apr 2012
Article Copyright 2012 by Paulo Zemek
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid