logo
down
shadow

Using Task.Factory.StartNew in a loop


Using Task.Factory.StartNew in a loop

By : czbarcea
Date : November 19 2020, 03:54 PM
may help you . Imagine the order of execution. You instruct every task to output i after a second, but by that time the loop has finished execution and i is equal to 100.
You can use the following StartNew overload to pass a state object which will be used by your action:
code :
public Task StartNew(Action<object> action, object state)
for (int i = 0; i < 100; i++)
{
    tasks.Add(Task.Factory.StartNew(o =>
    {
        int value = (int)o;

        Thread.Sleep(1000);
        Console.WriteLine(value.ToString() + "  " + Thread.CurrentThread.ManagedThreadId);
    }, i));
}


Share : facebook icon twitter icon
Why does task wait for Task.Run before executing next code but not for Task.Factory.StartNew?

Why does task wait for Task.Run before executing next code but not for Task.Factory.StartNew?


By : OflDevUser
Date : March 29 2020, 07:55 AM
should help you out The link you posted in your question has the answer: Task.Run understands and unwraps async Task delegates, while StartNew returns a Task instead, which you have to unwrap yourself by calling Unwrap or doing a double-await.
However, I recommend you completely rewrite the code as follows. Notes:
code :
public async Task<bool> PopulateListTaskRunAsync(CancellationToken cancellationToken)
{
  try
  {
    // Clear the records out first, if any
    Records.Clear();

    for (var i = 0; i < 10; i++)
    {
      cancellationToken.ThrowIfCancellationRequested();

      Records.Add(new Model
      {
        Name = NamesList[i],
        Number = i
      });

      Status = "cur: " + i.ToString(CultureInfo.InvariantCulture);

      // Artificial delay so we can see what's going on
      await Task.Delay(200);
    }

    Records[0].Name = "Yes!";
    return true;
  }
  catch (Exception)
  {
    return false;
  }
}
Is there any difference between Task.Factory.StartNew<T> & Task<T>.Factory.StartNew?

Is there any difference between Task.Factory.StartNew<T> & Task<T>.Factory.StartNew?


By : Jamal Erradi
Date : March 29 2020, 07:55 AM
wish helps you From the MSDN documentation for both the functions:
For TaskFactory.StartNew: Calling StartNew is functionally equivalent to creating a Task using one of its constructors...
Is Task.Run or Task.Factory.StartNew are bad practice for windows phone or any other client platform?

Is Task.Run or Task.Factory.StartNew are bad practice for windows phone or any other client platform?


By : user3595597
Date : March 29 2020, 07:55 AM
seems to work fine Stephen toub's article says that exposing asynchronous wrappers for synchronous methods in a library is bad. That adds no value. If the developer wants, he can always call Task.Run(()=> SomeSynchronousMethod());. There is no need to expose it in a library. If it is an application, yes you can, because that is the only way you can off load the work.
Same applies to "Newtonsoft.Json". because it is a library.
Task scheduler: when awaiting in a Task.Factory.StartNew, is the thread returned to the pool?

Task scheduler: when awaiting in a Task.Factory.StartNew, is the thread returned to the pool?


By : Roman Grom
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Here an example of a TaskWorker, that will not produce countless worker threads.
The magic is done by awaiting SemaphoreSlim.WaitAsync() which is an IO task (and there is no thread).
code :
class TaskWorker
{
    private readonly SemaphoreSlim _semaphore;

    public TaskWorker(int maxDegreeOfParallelism)
    {
        if (maxDegreeOfParallelism <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism));
        }

        _semaphore = new SemaphoreSlim(maxDegreeOfParallelism, maxDegreeOfParallelism);
    }

    public async Task RunAsync(Func<Task> taskFactory, CancellationToken cancellationToken = default(CancellationToken))
    {
        // No ConfigureAwait(false) here to keep the SyncContext if any
        // for the real task
        await _semaphore.WaitAsync(cancellationToken);
        try
        {
            await taskFactory().ConfigureAwait(false);
        }
        finally
        {
            _semaphore.Release(1);
        }
    }

    public async Task<T> RunAsync<T>(Func<Task<T>> taskFactory, CancellationToken cancellationToken = default(CancellationToken))
    {
        await _semaphore.WaitAsync(cancellationToken);
        try
        {
            return await taskFactory().ConfigureAwait(false);
        }
        finally
        {
            _semaphore.Release(1);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        var worker = new TaskWorker(1);
        var cts = new CancellationTokenSource();
        var token = cts.Token;

        var tasks = Enumerable.Range(1, 10)
            .Select(e => worker.RunAsync(() => SomeWorkAsync(e, token), token))
            .ToArray();

        Task.WhenAll(tasks).GetAwaiter().GetResult();
    }

    static async Task SomeWorkAsync(int id, CancellationToken cancellationToken)
    {
        Console.WriteLine($"Some Started {id}");
        await Task.Delay(2000, cancellationToken).ConfigureAwait(false);
        Console.WriteLine($"Some Finished {id}");
    }
}
class TaskWorker : IDisposable
{
    private readonly CancellationTokenSource _cts = new CancellationTokenSource();
    private readonly SemaphoreSlim _semaphore;
    private readonly int _maxDegreeOfParallelism;

    public TaskWorker(int maxDegreeOfParallelism)
    {
        if (maxDegreeOfParallelism <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism));
        }

        _maxDegreeOfParallelism = maxDegreeOfParallelism;
        _semaphore = new SemaphoreSlim(maxDegreeOfParallelism, maxDegreeOfParallelism);
    }

    public async Task RunAsync(Func<Task> taskFactory, CancellationToken cancellationToken = default(CancellationToken))
    {
        ThrowIfDisposed();

        using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token))
        {
            // No ConfigureAwait(false) here to keep the SyncContext if any
            // for the real task
            await _semaphore.WaitAsync(cts.Token);
            try
            {
                await taskFactory().ConfigureAwait(false);
            }
            finally
            {
                _semaphore.Release(1);
            }
        }
    }

    public async Task<T> RunAsync<T>(Func<Task<T>> taskFactory, CancellationToken cancellationToken = default(CancellationToken))
    {
        ThrowIfDisposed();

        using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token))
        {
            await _semaphore.WaitAsync(cts.Token);
            try
            {
                return await taskFactory().ConfigureAwait(false);
            }
            finally
            {
                _semaphore.Release(1);
            }
        }
    }

    private void ThrowIfDisposed()
    {
        if (disposedValue)
        {
            throw new ObjectDisposedException(this.GetType().FullName);
        }
    }

    #region IDisposable Support
    private bool disposedValue = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                _cts.Cancel();
                // consume all semaphore slots
                for (int i = 0; i < _maxDegreeOfParallelism; i++)
                {
                    _semaphore.WaitAsync().GetAwaiter().GetResult();
                }
                _semaphore.Dispose();
                _cts.Dispose();
            }
            disposedValue = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }
    #endregion
}
Whether to convert from Task<>.Factory.StartNew / Task.Factory.ContinueWhenAll() to async/await?

Whether to convert from Task<>.Factory.StartNew / Task.Factory.ContinueWhenAll() to async/await?


By : anoupi
Date : March 29 2020, 07:55 AM
like below fixes the issue You should definitely refactor it to async/await if you can make the Get*Rates methods asynchronous. In your current code you execute them on separate threads only to block the threads waiting for I/O to complete. That's a waste.
If you can make these methods asynchronous, the code might look like this:
Related Posts Related Posts :
  • How to get all ip address in LAN?
  • send value to controller using html.actionlink
  • Assembly "Microsoft.GeneratedCode" loaded
  • count the number of items in view in asp.net mvc
  • Shortcut Keys for Saving or Editing Record in C#
  • Very tricky/complex text formatting: How can I output a string[][] as a table?
  • Fill multiple textboxes after selecting a data from DropDownList in ASP.NET
  • How to launch an application after another is logged in in C#?
  • Unable to retrieve column values from one of the tables joined in a stored procedure?
  • Directories last file name display only
  • Why do I get a COMException when I try to initialize an Interop.Word.Application?
  • Finding subtotal for column in repeater control
  • dropdownlist item selected throw exception (stack empty)
  • How can I list IIS working processes programmatically?
  • How to access nested object from JSON with Json.NET in C#
  • OpenXml DataValidation set predefined List for columns
  • How to find recurring word groups in text with C#?
  • layout conrols to developp universal apps in windows 8.1 pro
  • Adding strings to a list via for loop xna
  • Using Vertex Arrays with OpenTK
  • Optimizing List<string>
  • C# Local variables
  • How can I merge the results of a group by Linq-to-XML query?
  • How to add Report in ASP.NET Project
  • C# How to display all instances of a loop in a label?
  • C# subscribe a function to System.Action that is subscribed to another System.Action: why does order matter?
  • Is there any negative effect to setting SqlCommand's CommandTimeout to a high value?
  • C# - TreeView Context Menu Out of Place when using keyboard
  • How to read stored procedure output and return it as list
  • How do you maintain changes made by VisualState triggers after setting another VisualState?
  • Should I be unit testing my bootstrapper and if so how?
  • using .SingleOrDefault() inside .Where() will raise the following exception:- System.NotSupportedException was unhandled
  • C# How would I fill a Form1 Parameter in the same seperate class
  • Access gridview row's data from LinkButton inside that row
  • Translating excel function to c# Math.pow not resulting in same values
  • Arranging Ten Inputted Numbers into Ascending and Descending order
  • AsEnumerable and Query Syntax
  • How can I defensively code against randomly referencing "Table 0" and null values?
  • Changing xaml code position based on screen size
  • Castle Windsor resolve ienumerable and name
  • Drawing multiple sprites with a for loop xna 4.0
  • For loop to Populate Textblocks
  • Visual Studio 2015: Create an Empty Project
  • What are .NET classes to replace the old MSXML2.ServerXMLHTTP?
  • Handle leak in .Net threads
  • Excel add-in ribbon click events bubbling
  • validation rule needed for only numbers to be entered
  • Parsing complex XML, no descendent elements exists when selecting a named element
  • Web Api - IEnumerable with complex type as param is null
  • Email address input validation
  • .Net AND operator Regular Expression using strings in a document
  • Windows phone 8.1 POST x-www-form-urlencoded not working
  • Is there any way to make my C# XMLManager work?
  • ASP.NET 5 Console Application (package) - How to create DBContext from connection string?
  • How to use form's function in other class C#
  • WPF Zebra EPL2 Printing issue
  • C# use reflection to capture exception throw
  • Convert strings in DataRow to double
  • Xml-Serialization is not working
  • HTML Agility Pack can't find classes with trailing spaces
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co