尝试使用异步任务时,我感到困惑。如果我在没有参数的情况下使用这个方法,一切都很好,但是当我向它添加参数时,它说不能将 System.Threading.Tasks.Task 转换为 System.Func。那么如何正确使用它并修复这个错误呢?
主要的:
Timers t = new Timers();
public Form1()
{
InitializeComponent();
t.StartTimerTemplate(TEMPLATEupdateSong("test", "test", "test"));//error occurs in this line
}
async Task TEMPLATEupdateSong(string url, string sender, string labelName)
{
string nowPlaying = await getter.getString(url);
nowPlaying = XDocument.Parse(nowPlaying).ToString();
var outputLabel = this.Controls.OfType<Label>()
.FirstOrDefault(control => control.Name == labelName);
outputLabel.Invoke(new Action(() =>
outputLabel.Text = sender + "\n" + nowPlaying
));
}
定时器.cs:
public void StartTimerTemplate(Func<Task> updateTemplate)
{
System.Timers.Timer timer = new System.Timers.Timer(50000);
timer.AutoReset = true;
timer.Elapsed += (sender, e) => timer_Elapsed(sender, e, updateTemplate());
timer.Start();
}
async void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e, Task task)
{
await task;
}
您的方法需要 a Func<Task>
,而不是 a Task
。
t.StartTimerTemplate(() => TEMPLATEupdateSong("test", "test", "test"));
或者
t.StartTimerTemplate(async () => await TEMPLATEupdateSong("test", "test", "test"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句