我有以下多线程代码,它取一个服务器列表,async运行重度操作,繁重的操作返回结果,我尝试用结果填充一个多行文本框(作为批处理完成时或当每个任务返回时,我已经添加了一些代码来希望执行这个任务,但是下面的三行以及右边的注释导致我们混淆虚空对静态和对象的无效:(任何关于我需要更改的提示都有很多提示。 ...谢谢
这是代码: -
public partial class Form1 : Form
{
Progress<string> progressReporter = new Progress<string>();
CancellationTokenSource cancelSource;
public Form1()
{
InitializeComponent();
progressReporter.ProgressChanged += progressManager_ProgressChanged;
}
async private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
btnCancel.Enabled = true;
cancelSource = new CancellationTokenSource();
textBox1.Text = await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token); //--Cannot implicity convert type 'void' to 'string'
await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token);
lblStatus.Text = "Completed.";
btnStart.Enabled = true;
btnCancel.Enabled = false;
}
static async Task PerfromTaskAction(CancellationToken ct)
{
StringBuilder sb = new StringBuilder();
object[] arrObjects = new object[] { "SERVER1", "SERVER2", "SERVER3", "SERVER4" };
IList<Task> tasks = new List<Task>();
foreach (object i in arrObjects)
{
if (ct.IsCancellationRequested) break;
sb.Append(string.Format("{0}", tasks.Add(Task.Run(() => HeavyOperation(i.ToString()))))); //-- Argument 2: cannot convert from 'void' to 'object'
tasks.Add(Task.Run(() => HeavyOperation(i.ToString())));
}
await Task.WhenAll(tasks).ConfigureAwait(false);
return sb.ToString(); //--Since 'Form1.PerfromTaskAction(CancellationToken)' is an async method that returns 'Task', a return keyword must not be followed by an object expression?
}
void progressManager_ProgressChanged(object sender, string e)
{
lblStatus.Invoke((Action)(() => lblStatus.Text = e));
}
static string HeavyOperation(string i)
{
PowerShell ps = PowerShell.Create();
ps.AddCommand("invoke-command");
ps.AddParameter("computername", i);
ps.AddParameter("scriptblock", ScriptBlock.Create("get-vmreplication | select State"));
Collection<PSObject> result = ps.Invoke();
return(result[0].Properties["State"].Value.ToString());
}
private void btnCancel_Click(object sender, EventArgs e)
{
cancelSource.Cancel();
}
}
答案 0 :(得分:2)
你有三个错误,所以一次只取一个错误:
//-- Argument 2: cannot convert from 'void' to 'object'
sb.Append(string.Format("{0}", tasks.Add(Task.Run(() => HeavyOperation(i.ToString())))));
List<T>.Add
的返回类型为void
。因此它不能用作string.Format
的第二个参数。在这里一点也不清楚你想要使用这行代码,所以我不能建议修复。
//--Since 'Form1.PerfromTaskAction(CancellationToken)' is an async method that returns 'Task', a return keyword must not be followed by an object expression
return sb.ToString();
此错误表示您使用的是async Task
方法(与void
的异步等效项),因此它不能具有返回值。但是你的代码却试图返回一个值。
此处的修复方法是更改方法签名以返回Task<string>
:
static async Task<string> PerfromTaskAction(CancellationToken ct)
至于最后的错误:
//--Cannot implicity convert type 'void' to 'string'
textBox1.Text = await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token);
如果PerformTaskAction
返回Task
,则返回类型Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token)
也是Task
,这意味着await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token)
的类型为{{1} }}。而且您无法获取void
并将其分配给void
。
最后一个错误的修复程序(更改为textBox1.Text
)也修复了这个错误。 Task<string>
的返回类型现为Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token)
,Task<string>
的类型现为await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token)
。
从评论中更新:
由于您希望在完成所有字符串后返回所有字符串,因此更轻松 string
:
StringBuilder
请注意,由于static async Task<string> PerfromTaskAction()
{
object[] arrObjects = new object[] { "SERVER1", "SERVER2", "SERVER3", "SERVER4" };
var tasks = arrObjects.Select(i => Task.Run(() => HeavyOperation(i.ToString())));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
return string.Join("", results);
}
中未使用CancellationToken
,因此可以从HeavyOperation
签名中删除它。
答案 1 :(得分:0)
将方法签名更改为
static async Task<string> PerfromTaskAction(CancellationToken ct)
return Task(sb.ToString());
然后
textBox1.Text = await Task.Run(() => PerfromTaskAction(cancelSource.Token), cancelSource.Token).Result;