任务似乎自动启动 [英] Tasks seem to start automatically

查看:127
本文介绍了任务似乎自动启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我移植一个程序,有哪些是没有改善,当我将它移植,因为缓慢是因为访问数据库服务器(而不是次优code)条很长的加载时间。我提出了装载到与任务库现在的用户界面不会冻结,因为它加载一个独立的线程,但它的确让我对某事感到好奇:

I'm porting a program that had a very long loading time which was not improved at all when I ported it, as the slowness was because of accessing a db-server (and not sub-optimal code). I have moved the loading onto a separate thread with the Tasks library and now the UI doesn't freeze as it loads, but it did make me curious about something:

Task.Factory 对象有一个方法 StartNew 这是为了创建一个新任务,启动它,并返回对它的引用。这是有道理的,但似乎工作构造函数做同样的事情。

The Task.Factory object has a method StartNew which is supposed to create a new task, start it, and return a reference to it. This makes sense, but it seems that the Task constructor does the exact same thing.

当我做到以下几点:

Task catsFromDB = new Task(() => AddCategoriesFromDB(cts.Token), cts.Token);
catsFromDB.Start();

我得到一个错误 InvalidOperationException异常,我真的不明白。这似乎相信,我已经踢它关闭了。我还没有。

I get an error InvalidOperationException which I really don't understand. It seems to believe that I've kicked it off already. Which I haven't.

该erorr是:InvalidOperationException异常,开始可能不会被要求已完成的任务

The erorr is: "InvalidOperationException, Start may not be called on task that has completed"

错误是一些抵消code我在内。我需要尝试重新运行之前重置取消。

The error was some cancellation code I included. I needed to reset the cancellation before trying to run it again.

推荐答案

现在我觉得自己很蠢,但是这将是有益的,让从我的'绿色'学习别人(如新,经验不足)的错误:

Now I feel stupid, but it will be instructive to let others learn from my 'green' (as in "new", "inexperienced") error:

我需要有问题的操作要撤销并重新运行的,所以我已经实现,它总是得到这样的实际负荷前运行CancelLoad操作。事实证明,我忘了创建取消和等待后,一个新的令牌。

I needed the operation in question to be cancellable and re-runnable, so I had implemented a "CancelLoad" operation which always got run before doing the actual load. It turns out that I forgot to create a new Token after canceling and waiting.

这篇关于任务似乎自动启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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