【问题标题】:How to use async task as a method with parameters如何使用异步任务作为带参数的方法
【发布时间】:2019-10-01 07:36:02
【问题描述】:

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

【问题讨论】:

    标签: c# multithreading asynchronous task func


    【解决方案1】:

    您的方法需要Func&lt;Task&gt;,而不是Task

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

    或者

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

    【讨论】:

      猜你喜欢
      • 2023-02-15
      • 2014-05-04
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 2015-03-30
      • 2013-09-14
      相关资源
      最近更新 更多