Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, August 2, 2020

C#: Async ParallelForEach

Here's an example of using ParalleForEach Async in C#

        /// <summary>
        /// Extension method for ParallelForEachAsync
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="dop"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static Task ParallelForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
        {
            async Task AwaitPartition(IEnumerator<T> partition)
            {
                using (partition)
                {
                    while (partition.MoveNext())
                    { await body(partition.Current); }
                }
            }

            return Task.WhenAll(
                Partitioner
                    .Create(source)
                    .GetPartitions(dop)
                    .AsParallel()
                    .Select(p => AwaitPartition(p)));
        }

Usage:

#region Extension method for ParallelForEachAsync: usage
       
        //await GetDocumentsFromDatabase(session).ForEachAsync(dop: 20, body: async entry =>
        //{
        //    _logger.Info($"Processing entry '{entry.Id}'");
        //});

#endregion

Wednesday, April 18, 2018

Friday, February 12, 2016

Friday, November 6, 2015

Generate a comma separated string from an IEnumerable object

string.join(",", Contacts.Select(x=>x.Name); //Name is a property of an object(Contact) in the list of Contacts

Wednesday, November 4, 2015

Simple yet effective way to find if IEnumerable has elements or not

bool IsEmpty(IEnumerable en)
{
    foreach(var c in en) { return false; }
    return true;
}

Monday, October 19, 2015

C# code to get numbers after decimal point

int decimalPoints=BitConverter.GetBytes(Decimal.GetBits(value)[3])[2];

Tuesday, October 28, 2014

Great example of async and await

http://blog.roboblob.com/2014/10/23/awaiting-for-that-button-click/

Saturday, October 4, 2014

Enums as bitarray

http://blog.falafel.com/entity-framework-enum-flags/

Monday, September 29, 2014

Threading concepts explained in detail

http://www.codeproject.com/Articles/821074/Net-Threading-You-Need-To-Know

Thursday, August 28, 2014

Asynchronous Tasks Simplified

Superb article and nice explanation
http://visualstudiomagazine.com/articles/2014/08/01/manage-asynchronous-tasks.aspx

Wednesday, July 23, 2014

Implement IEquatable in a Generic Type

http://csharp.2000things.com/2014/07/22/1143-implement-iequatable-in-a-generic-type/

Tuesday, June 24, 2014

How to Concatenate Collections into Strings

http://visualstudiomagazine.com/blogs/tool-tracker/2014/06/join-collections-into-strings.aspx