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

梦想的初衷 提交于 2019-12-07 02:12:05

问题


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.


回答1:


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);



回答2:


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);
    



回答3:


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).




回答4:


You are calling the wrong overload. If you want to pass a TaskScheduler, use this:

Task.Factory.StartNew( () => { ... }, CancellationToken.None, TaskCreationOptions.None, ui );



回答5:


If you want to specify a TaskScheduler in your call to Task.Factory.StartNew() you need to use one of the overloads that accepts it as an argument. You are calling the overload

StartNew(Action<object> action, object state)

which is probably not what you intended?

To use Task.Factory.StartNew() with a scheduler you also need to specify a CancellationToken and some TaskCreationOptions, that is the method documented here.



来源:https://stackoverflow.com/questions/7780812/how-may-i-resolve-this-error-delegate-system-actionobject-does-not-take-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!