如何将异步任务用作带参数的方法

How to use async task as a method with parameters

我在尝试使用异步任务时感到困惑。如果我使用这个没有参数的方法一切都很好,但是当我向它添加参数时,它说不能将 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;
}

您的方法需要 Func<Task>,而不是 Task

 t.StartTimerTemplate(() => TEMPLATEupdateSong("test", "test", "test"));

或者

t.StartTimerTemplate(async () => await TEMPLATEupdateSong("test", "test", "test"));