C
C#2y ago
?

How do I pass 1 argument in lambda expression?

string tempTitle = "whatever";

await Task.Run(async (tempTitle) => // here I am having some errors, no idea how to pass this tempTitle variable inside this task to avoid cross-thread exception
{
Text = "Complete!";
await Task.Delay(5000);
Text = tempTitle;
});
string tempTitle = "whatever";

await Task.Run(async (tempTitle) => // here I am having some errors, no idea how to pass this tempTitle variable inside this task to avoid cross-thread exception
{
Text = "Complete!";
await Task.Delay(5000);
Text = tempTitle;
});
Maybe I need to put Action<string> somewhere? Hmm
6 Replies
DaVinki
DaVinki2y ago
Task.Run doesn't accept an Action<T> But you are able to use tempTitle inside of the function Anonymous functions are able to use variables previously declared in scope but be careful about it
?
?OP2y ago
string tempTitle = "something";

await Task.Run(async () =>
{
Text = "Complete!";
await Task.Delay(5000);
Text = tempTitle;
});
string tempTitle = "something";

await Task.Run(async () =>
{
Text = "Complete!";
await Task.Delay(5000);
Text = tempTitle;
});
Is that what you meant? Then I have unhandled exception
DaVinki
DaVinki2y ago
Is Text a variable you already declared?
?
?OP2y ago
No, this is a property of a form, Windows Forms framework
DaVinki
DaVinki2y ago
So what does the error say?
?
?OP2y ago
As on the previous screenshot, Exception Unhandled Cross-thread operation not valid But you gave me something to wonder, it's not an issue with my string but accessing this "Text" property, I need to check if an invoke is required, hold on please
await Task.Run(async () =>
{
if(InvokeRequired)
{
Invoke(TitlePointer, "Complete!");
}
else
{
TitlePointer("Complete!");
}

await Task.Delay(6_000);

if(InvokeRequired)
{
Invoke(TitlePointer, tempTitle);
}
else
{
TitlePointer(tempTitle);
}
});
await Task.Run(async () =>
{
if(InvokeRequired)
{
Invoke(TitlePointer, "Complete!");
}
else
{
TitlePointer("Complete!");
}

await Task.Delay(6_000);

if(InvokeRequired)
{
Invoke(TitlePointer, tempTitle);
}
else
{
TitlePointer(tempTitle);
}
});
Yeah, that was my mistake and not issue with my string but accessing that "Text" property. Thanks @daVinki a lot! The above script works now and my program runs without cross-thread exception catpog
Want results from more Discord servers?
Add your server