我有以下多线程代码,它采取服务器列表和异步运行繁重的操作,繁重的操作返回结果,并试图填充多行文本框的结果(作为批处理完成或作为每个任务返回),我已经添加了一些代码,希望执行这项任务,但下面三行与正确的意见导致我们混淆关于无效静态和无效的对象:(任何提示大大收到我需要改变.. ..谢谢将void转换为字符串 - void对象问题?
这里是代码: -
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();
}
}
1.你的问题是什么? 2. *“'void' to object”*没有任何意义 - 'void'意味着一个方法不会返回任何东西,您不能将“nothing”转换为一个对象(并且它看起来并没有在代码中发生?)3.所有这些代码应该显示什么?它绝对不是[mcve] – UnholySheep
如果你想要返回字符串,将方法改为静态异步任务' –
“将void转换为字符串”...我会阻止你。 – Abion47