传递使用Task.Factory.StartNew方法参数 [英] Passing a method parameter using Task.Factory.StartNew

查看:819
本文介绍了传递使用Task.Factory.StartNew方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

var task = Task.Factory.StartNew(CheckFiles, cancelCheckFile.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

private void CheckFiles()
{
  //Do stuff
}

我现在想修改CheckFiles接受和整数和BlockingCollection参考

I now want to amend CheckFiles to accept and integer and a BlockingCollection reference

private void CheckFiles(int InputID, BlockingCollection<string> BlockingDataCollection)
{
  //Do stuff
}

我似乎无法找到一个方法来启动这个任务,因为我做上面。

I can't seem to find a way to Start this task as I did above.

你能帮忙吗?

感谢

推荐答案

最好的办法可能是使用lambda EX pression是关闭了,你要显示的变量。

The best option is probably to use a lambda expression that closes over the variables you want to display.

不过,要小心在这种情况下,特别是如果你调用这个在一个循环。 (我提到这一点,因为你的变量是一个身份证,这是常见的这种情况。)如果你关闭了该变量在错误的范围内,就可以得到一个错误。有关详细信息,请参阅<一href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx">Eric利珀特的帖子关于这个问题。这通常需要制作一个临时的:

However, be careful in this case, especially if you're calling this in a loop. (I mention this since your variable is an "ID", and this is common in this situation.) If you close over the variable in the wrong scope, you can get a bug. For details, see Eric Lippert's post on the subject. This typically requires making a temporary:

foreach(int id in myIdsToCheck)
{
    int tempId = id; // Make a temporary here!
    Task.Factory.StartNew( () => CheckFiles(tempId, theBlockingCollection),
         cancelCheckFile.Token, 
         TaskCreationOptions.LongRunning, 
         TaskScheduler.Default);
}

另外,如果你的code是像上面的,你应该小心使用 LongRunning 提示 - 使用默认的调度,这使得每个任务获得它自己的专用线而不是使用线程池。如果您正在创建很多任务,这很可能会产生负面影响,因为你不会得到线程池的优势。它通常面向单一,长期运行的任务(因此它的名字),没有的东西,将实施工作,对集合的项目,等等。

Also, if your code is like the above, you should be careful with using the LongRunning hint - with the default scheduler, this causes each task to get its own dedicated thread instead of using the ThreadPool. If you're creating many tasks, this is likely to have a negative impact as you won't get the advantages of the ThreadPool. It's typically geared for a single, long running task (hence its name), not something that would be implemented to work on an item of a collection, etc.

这篇关于传递使用Task.Factory.StartNew方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆