Reputation: 425
Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
I want to run function in enother thread and I can do this without error, but only when calculating function is not void
. I want to use void function. Tell me please how to do it or what kind of result it should return?
private async void buttonStep3_Click(object sender, EventArgs e)
{
DialogResult dialogResult = folderBrowserDialog1.ShowDialog();
if (dialogResult != DialogResult.OK)
return;
SetAllButtonsStateEnabled(false);
progressBar1.Value = 0;
progressBar1.Visible = true;
var progressProgressBarValue = new Progress<int>(s => progressBar1.Value = s);
await Task.Run(() => SizeFilter3(
Convert.ToInt32(textBoxSF1W.Text), Convert.ToInt32(textBoxSF1H.Text),
Convert.ToInt32(textBoxSF2W.Text), Convert.ToInt32(textBoxSF2H.Text),
Convert.ToInt32(textBoxSF3W.Text), Convert.ToInt32(textBoxSF3H.Text),
Convert.ToInt32(textBoxSF4W.Text), Convert.ToInt32(textBoxSF4H.Text),
Convert.ToInt32(textBoxSF5W.Text), Convert.ToInt32(textBoxSF5H.Text),
progressProgressBarValue),
TaskCreationOptions.LongRunning);//this line gives an error
progressBar1.Visible = false;
progressBar1.Value = 0;
SetAllButtonsStateEnabled(true);
}
private void SizeFilter3(int filterW1, int filterH1,
int filterW2, int filterH2,
int filterW3, int filterH3,
int filterW4, int filterH4,
int filterW5, int filterH5,
IProgress<int> progressProgressBarValue)
{
//some actions
progressBarValue += progressBarProgress;
progressProgressBarValue.Report(progressBarValue);
//some actions
}
Upvotes: 4
Views: 1450
Reputation: 4733
You should use the Task factory to create a long running task, which accepts a lambda:
await Task.Factory.StartNew(() => SizeFilter3(Convert.ToInt32("0"), Convert.ToInt32("0"),
Convert.ToInt32("0"), Convert.ToInt32("0"),
Convert.ToInt32("0"), Convert.ToInt32("0"),
Convert.ToInt32("0"), Convert.ToInt32("0"),
Convert.ToInt32("0"), Convert.ToInt32("0"),
progressProgressBarValue), TaskCreationOptions.LongRunning);
Task.Run
doesn't have a TaskCreationOptions
argument.
Upvotes: 5
Reputation: 2590
You can cast your lambda expression explicitly into an Action
:
Task.Run((Action) (() => SizeFilter3(
Convert.ToInt32(textBoxSF1W.Text), Convert.ToInt32(textBoxSF1H.Text),
Convert.ToInt32(textBoxSF2W.Text), Convert.ToInt32(textBoxSF2H.Text),
Convert.ToInt32(textBoxSF3W.Text), Convert.ToInt32(textBoxSF3H.Text),
Convert.ToInt32(textBoxSF4W.Text), Convert.ToInt32(textBoxSF4H.Text),
Convert.ToInt32(textBoxSF5W.Text), Convert.ToInt32(textBoxSF5H.Text),
progressProgressBarValue)),
TaskCreationOptions.LongRunning);
Note that you have to put the expression in parentheses as well for this to work.
Upvotes: -1