当尝试使用异步任务时,我感到困惑。如果我使用不带参数的此方法,一切都很好,但是当我向其中添加参数时,它表示无法将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
));
}
Timers.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;
}
答案 0 :(得分:2)
您的方法需要Func<Task>
,而不是Task
。
t.StartTimerTemplate(() => TEMPLATEupdateSong("test", "test", "test"));
或
t.StartTimerTemplate(async () => await TEMPLATEupdateSong("test", "test", "test"));