logo
down
shadow

How can I wait for the last Task in the chain?


How can I wait for the last Task in the chain?

By : user2954202
Date : November 22 2020, 01:01 AM
will be helpful for those in need You can use Task.WaitAll(), which takes an array of tasks.
http://msdn.microsoft.com/en-us/library/dd270695(v=vs.110).aspx
code :
Tasks[] tasks = GetTasks();
var finalTask = Task.Factory.ContinueWhenAll(tasks, completedTasks => {...}); 
finalTask.Wait();


Share : facebook icon twitter icon
How do I chain a task to another task without knowing the first task's result type

How do I chain a task to another task without knowing the first task's result type


By : user3424873
Date : March 29 2020, 07:55 AM
I wish this help you You could use dynamic typing to call a generic method with type inference provided by the dynamic typing:
code :
private static object WrapTask(dynamic task)
{
    return WrapTaskImpl(task);
}

private static Task<T> WrapTaskImpl<T>(Task<T> task)
{
    return task.ContinueWith(parentTask => parentTask.Result,
        TaskContinuationOptions.ExecuteSynchronously);
}
private static Task<T> WrapTask<T>(object task)
{
    Task<T> realTask = (Task<T>) task;
    return realTask.ContinueWith(parentTask => parentTask.Result, 
                                 TaskContinuationOptions.ExecuteSynchronously);
}
var task = WrapTask<string>(CreateTask());

Console.WriteLine(task.Result);
Task.Result/wait(..) is indefinitely waits if waited on chain of tasks have 'unwrapped' task, whereas successfully compl

Task.Result/wait(..) is indefinitely waits if waited on chain of tasks have 'unwrapped' task, whereas successfully compl


By : ikrum hossain
Date : March 29 2020, 07:55 AM
wish of those help Okay, let's try to get to the bottom of what's happening here.
First things first: the difference in the lambda passed to your ContinueWith is insignificant: functionally that part is identical in the two examples (at least as far as I can see).
code :
static Task FooAsync()
{
    return Task.Delay(500);
}
// These two have similar behaviour and
// are interchangeable for our purposes.
Task.Run(() => Task.Delay(500))
Task.Run(async () => await Task.Delay(500));
Task.Factory.StartNew(() => Task.Delay(500))
for (int i = 1; i <= 5; i++)
{
    var ct = FooAsync().ContinueWith(_ => { }, TaskContinuationOptions.AttachedToParent);
    childTasks.Add(ct);
}
static async Task TaskWhichUsedToWorkButNotAnymore()
{
    List<Task> tasks = new List<Task>();
    Task task = FooAsync();
    tasks.Add(task);
    Task<Task> continuationTask = task.ContinueWith(async t =>
    {
        List<Task> childTasks = new List<Task>();
        for (int i = 1; i <= 5; i++)
        {
            var ct = FooAsync();
            childTasks.Add(ct);
        }
        Task wa = Task.WhenAll(childTasks.ToArray());
        await wa.ConfigureAwait(continueOnCapturedContext: false);
    }, TaskContinuationOptions.OnlyOnRanToCompletion);
    tasks.Add(continuationTask);

    // Let's Unwrap the async/await way.
    // Pay attention to the return type.
    // The resulting task represents the
    // completion of the task started inside
    // (and returned by) the ContinueWith delegate.
    // Without this you have no reference, and no
    // way of waiting for, the inner task.
    Task unwrappedTask = await continuationTask;

    // Boom! This method now has the
    // same behaviour as the other one.
    tasks.Add(unwrappedTask);

    await Task.WhenAll(tasks.ToArray());

    // Another way of "unwrapping" the
    // continuation just to drive the point home.
    // This will complete immediately as the
    // continuation task as well as the task
    // started inside, and returned by the continuation
    // task, have both completed at this point.
    await await continuationTask;
}
Why if I try to stop a task using CancellationToken.Cancel() then the actual task get stucked on Task.Wait()?

Why if I try to stop a task using CancellationToken.Cancel() then the actual task get stucked on Task.Wait()?


By : user1426713
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Task.Wait() is synchronous. If it happens that due to an Invoke() call you can return to this method, you get a deadlock. Use the debugger to inspect the state of your callstack when you have reached the stucked state.
How to wait for task completes with celery chain?

How to wait for task completes with celery chain?


By : wangdong8500
Date : March 29 2020, 07:55 AM
Does that help To expand @bruno's comment: use chord and modify the editOgTags function to create a group that chords to the notification:
code :
from celery import chord

@shared_task(ignore_result=True)
def editOgTags(products, title, description, whichImage, readableShopname, currentThemeId, name, email, totalProducts):
    tasks = []
    for product in products:
        tasks.append(editOgTitle.si(product, title, readableShopname))
        tasks.append(editOgDescription.si(product, description, readableShopname))
        tasks.append(editOgImage.si(product, int(whichImage), currentThemeId))
    # kick off the chord, notifyBulk... will be called after all of these 
    # edit... tasks complete.
    chord(tasks)(notifyBulkEditFinish.si(email, name, readableShopname, totalProducts))
How to stop chain execution for failing task in the middle of a chain?

How to stop chain execution for failing task in the middle of a chain?


By : user3674371
Date : March 29 2020, 07:55 AM
Any of those help Got the answer from celery-users group, hopefully it will help someone else. All the credits go to Ing. Josue Balandrano Coronel.
code :
@app.task(bind=True)
def success(self, result):
    print(f"Chain result: ${result}")
    print(f"Chain: ${self.chain}")

@app.task(bind=True)
def error(self, *args, **kwargs)
    print(f"args: ${args)")
    print(f"kwargs: ${kwargs}")

if __name__ == "__main__":
    fails_in_the_middle = (ok.s(1) | fail.s() | ok.s() | success.s()).on_error(error.s())
    fails_in_the_end = (ok.s(1) | fail.s() | success.s()).on_error(error.s())
resp = c.delay()
for result in list(resp.collect(intermediate=True)):
    print(result.get())
resp = c.delay()
parent = resp.parent

while parent is not None:
    parent = resp.parent

for child in parent.children:
    child.get() 
Related Posts Related Posts :
  • Console application doesn't obey Thread.Join
  • System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
  • Creating a scripting environment for a C# program
  • Is it reasonable to replace .Equals with a method rather than override it?
  • How I can capture multiple keys?
  • How to have all my classes default functionalities like .ToString method
  • Business Object properties: model as Objects or Enums?
  • Loading this assembly would produce a different grant set from other instances
  • How to call a method without first calling it's constructor in C#
  • Can't set a date time in one of my entity framework objects, says NullReferenceException
  • GETJob() Win32 Print spooler api 64bit The parameter is incorrect, how to fix?
  • Switch Case Causing Trouble In Going To A particular Function
  • Switch Case Calling A Function Based On The User's Choice
  • Accessing WebBrowser on different Threads
  • CPU Usage Avoid 100% With Environment.ProcessorCount?
  • Select distinct categories from database
  • C# app getting Watson dialog when calling TerminateProcess
  • The underlying provider failed on Open in entity framework connection
  • Compile a library without checking references
  • Can we create and access a registry key in HKEY_LOCAL_MACHINE without running application with admin permissions in C#
  • Control light intensity with a UI slider
  • Threading (Does these threads exits or aborts itself?)
  • Change the function of a button if Logged in
  • how to accept value in date format in textbox in C# windows form?
  • remove the lines from RichtextBox?
  • How to call String.Split that takes string as separator?
  • Specify task timeout in parallel linq to objects
  • comparing two custom objects to prevent duplicates
  • How to Print Text from ComboBox into a MessageBox
  • How can I do a Func<object[],Expression<Func<T,bool>>> dynamic?
  • C# SqlDataReader No data exists for the row/column
  • My code is not giving the desired output
  • Is it possible to have multiple MVC routes point to the same controller/view?
  • Updating Listbox results in " Invalid cross-thread access."
  • Finding Elbow Angle with Kinect
  • Host a mvc web api application in the sub-folder of a website
  • How to generate a sequential unique id in a thread-safe way
  • How to add a separator to a WPF combobox that is databound?
  • optimize linq query with related entities
  • Optimize this code for large input
  • Is there any way to clear all list box short way?
  • ACR122 Device Programming sample does not find reader
  • Parallel Library: does a delay on one degree of parallelism delay all of them?
  • How to convert a var which contains Long to an Long[]
  • Quickly prune and create valid data combinations
  • Get 3 parameters out of a Dictionary<string, Dictionary<string Action>>
  • Regex IsMatch taking too long to execute
  • Shuffling divs using C# behindcode
  • ASP.NET Project and IE10 Compatibility Mode issues in Windows 7
  • Why can't I loop through this dictionary?
  • RavenDB Stream for Unbounded Results - Connection Resilience
  • How to remove the focus border of a CheckBox in C# Visual Studio?
  • Exception while using String.Format "Index (zero based) must be greater than or equal to zero and less than the siz
  • Caching an LDAP connection
  • C# How to detect kill event sender
  • How to Display Splashscreen and login form at same time using c#
  • Read .sql script with parameters
  • Why would I need to compile/generate methods/code at runtime?
  • Unable to create a constant value of type 'Project.Models.Subcategory'. Only primitive types or enumeration types are su
  • How to run possibly synchronous or possibly asynchronous code?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org