C# - 将 UI 引用发送到 Task.Factory.StartNew();?
您将如何发送/传递对新任务的实例引用?
假设我已经得到了这个:
public BlockingCollection<string> blockingCollection = new BlockingCollection<string>();
textBox_txt.Text = "Result: ";
public Task t = Task.Factory.StartNew(() =>
{
foreach (string value in *???1*.blockingCollection.GetConsumingEnumerable())
{
*???1*.blockingCollection.Take()
[...bla...]
*???2*.Invoke(new updateTextBox_txtCallback(*???2*.updatetextBox_txt)
, new object[] { "THE RESULT!\r\n" });
}
});
我猜在这里的某个地方 StartNew(() =>
我必须将引用传递给blockingContent 和textBox。我环顾四周,但是无法弄清楚语法。(这很麻烦)
请帮忙。
[编辑]所以,如果我从任务中调用静态对象,它显然可以工作;但我需要任务来处理实例;和 updateTextBox_txtCallback 调用。
How would you send/pass instance references to a new task?
Let's say I've got this:
public BlockingCollection<string> blockingCollection = new BlockingCollection<string>();
textBox_txt.Text = "Result: ";
public Task t = Task.Factory.StartNew(() =>
{
foreach (string value in *???1*.blockingCollection.GetConsumingEnumerable())
{
*???1*.blockingCollection.Take()
[...bla...]
*???2*.Invoke(new updateTextBox_txtCallback(*???2*.updatetextBox_txt)
, new object[] { "THE RESULT!\r\n" });
}
});
I'm guessing that somewhere in here StartNew(() =>
I have to pass the references to the blockingContent and to the textBox. I've looked around but couldn't figure out the syntax. (it's quite hairy)
Help, please.
[Edit] So, if I call a static object from withing the Task, it obviously works; but I need the task to work with instances; namely the blockingCollection and the updateTextBox_txtCallback Invoke.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我重现了您的问题,并在下面提供了解决方法。问题是您使用 Task 作为类中的字段,因此它只能引用静态成员,因为在运行构造函数之前尚未构造实例(在初始化类之前调用字段初始值设定项)。
来自 C# 规范 (10.5.5.2):
基本上你有两个选择:
构造函数
示例:
I reproduced your problem, with a workaround below. The problem is that you are using the Task as a field in your class so it can only refer to static members, as the instance hasn't been constructed until the constructor is run (the field initializers are called before the class is initialized).
From the C# specification (10.5.5.2):
Basically you have two options:
constructor
Example:
您不必传递引用,因为 C# 支持闭包。只需在
StartNew
块中使用保存该引用的变量,就会导致编译器生成代码,将您的引用打包到传递给匿名方法的状态对象中:我强烈推荐 闭包之美 了解有关此功能的更多信息。
现在,关闭对 UI 元素的引用的值是否是一个好主意是一个完全不同的讨论。
You don't have to pass the reference because C# supports closures. Simply using the variable holding that reference inside your
StartNew
block will cause the compiler to generate code that packages up you reference into state object that is passed to the anonymous method:I highly recommend The Beauty of Closures for more information on this feature.
Now whether or not it is a good idea to close over a value that is a reference to a UI element is a completely different discussion.