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