Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ValueTask support #254

Open
mikasoukhov opened this issue Apr 8, 2022 · 1 comment
Open

ValueTask support #254

mikasoukhov opened this issue Apr 8, 2022 · 1 comment
Assignees

Comments

@mikasoukhov
Copy link

Here is some my own extensions (maybe will be interested to join with Nito's code, like you proj and use it):

public static async ValueTask AsValueTask<T>(this ValueTask<T> valueTask)
			=> await valueTask;

		public static ValueTask<T> AsValueTask<T>(this Task<T> task)
			=> new(task);

		public static ValueTask AsValueTask<T>(this Task task)
			=> new(task);

		public static async ValueTask<T[]> WhenAll<T>(this IEnumerable<ValueTask<T>> tasks)
		{
			if (tasks is null)
				throw new ArgumentNullException(nameof(tasks));

			List<Exception> exceptions = null;

			var source = tasks.ToArray();

			var results = new T[source.Length];

			for (var i = 0; i < source.Length; i++)
			{
				try
				{
					results[i] = await source[i].ConfigureAwait(false);
				}
				catch (Exception ex)
				{
					exceptions ??= new List<Exception>(source.Length);
					exceptions.Add(ex);
				}
			}

			if (exceptions is not null)
				throw new AggregateException(exceptions);

			return results;
		}

		public static async ValueTask WhenAll(this IEnumerable<ValueTask> tasks)
		{
			if (tasks is null)
				throw new ArgumentNullException(nameof(tasks));

			List<Exception> exceptions = null;

			var source = tasks.ToArray();

			for (var i = 0; i < source.Length; i++)
			{
				try
				{
					await source[i].ConfigureAwait(false);
				}
				catch (Exception ex)
				{
					exceptions ??= new List<Exception>(source.Length);
					exceptions.Add(ex);
				}
			}

			if (exceptions is not null)
				throw new AggregateException(exceptions);
		}

		public static void Run(Func<ValueTask> getTask)
		{
			if (getTask is null)
				throw new ArgumentNullException(nameof(getTask));

			AsyncContext.Run(() => getTask().AsTask());
		}

		public static T Run<T>(Func<ValueTask<T>> getTask)
		{
			if (getTask is null)
				throw new ArgumentNullException(nameof(getTask));

			return AsyncContext.Run(() => getTask().AsTask());
		}
@StephenCleary StephenCleary self-assigned this May 18, 2022
@BalassaMarton
Copy link

It would be quite inconvenient to have this name for a static utility class now that there's void ValueTask.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants