Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How may I resolve this error? - Delegate 'System.Action<object>' does not take 0 arguments

Tags:

c#

task

The following code:

var ui = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() => { listBox1.Items.Add("Starting to crawl " + srMainSiteURL + "..."); } , ui);

is resulting in the following error:

Delegate 'System.Action<object>' does not take 0 arguments

After looking at other threads, I have not been able to determine nor understand the cause of the error. Please advise.

like image 579
MonsterMMORPG Avatar asked Oct 15 '11 21:10

MonsterMMORPG


3 Answers

Because you did use

public Task StartNew(Action<object> action, object state)

I do think you wanted to use

public Task StartNew(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler)

So your example would become:

Task.Factory.StartNew(() => { listBox1.Items.Add("Starting to crawl " + srMainSiteURL + "..."); }, CancellationToken.None, TaskCreationOptions.None, ui);
like image 111
Alois Kraus Avatar answered Nov 16 '22 05:11

Alois Kraus


You're trying to call StartNew(Action<object>, object). However, your lambda expression cannot be converted into an Action<object>.

Options:

  • Remove your second argument (ui) so that you end up calling StartNew(Action) which is fine for the lambda expression you've provided. For example:

    // The braces were redundant, by the way...
    Task.Factory.StartNew(() => listBox1.Items.Add("..."));
    
  • Change your lambda expression to accept a parameter:

    Task.Factory.StartNew(state => listBox1.Items.Add("..."), ui);
    
like image 4
Jon Skeet Avatar answered Nov 16 '22 05:11

Jon Skeet


You are using this one: TaskFactory.StartNew Method (Action, Object)

that takes an Action<object>, so you should write p => { ... }, the ui is the second parameter of StartNew (an object).

like image 1
xanatos Avatar answered Nov 16 '22 03:11

xanatos