【问题标题】:How to convert the return result from a Task?如何转换任务的返回结果?
【发布时间】:2017-07-04 11:01:16
【问题描述】:

我想使用 Task.Run 在队列中执行一个动作,并从动作中获取返回值,如果成功,将它们从队列中删除。 Queue 中的所有操作都返回类型Task<bool>。执行代码时,Action 成功执行,但 Task.Run 最终失败:

无法将“System.Threading.Tasks.Task”类型的对象转换为“System.Threading.Tasks.Task`1[System.Boolean]”类型。

下面的更新方法是作为任务从基类调用的:

public void Init()
{
    InitDaemon();

    KeepAliveTask = new Task(Run);
    KeepAliveTask.Start();
}

private void Run()
    while(_keepAlive)
    {  
        Update();
        Thread.Sleep(_updateMillSecs);
    }
}

当调用基类 Close() 方法时,_keepAlive 设置为 false。

void override Update()
{
    private static Task<bool> _currentTask;
    private static Queue<Action> _oisQueue = new Queue<Action>();

    // if there is at least one task in the queue and that task is complete
    if (_oisQueue.Count > 0 && (_currentTask == null || _currentTask.IsCompleted))
    {
        var action = _oisQueue.First();
        _currentTask = (Task<bool>)Task.Run(() => action());

        // if task was successful
        if (_currentTask.Result)
            _oisQueue.Dequeue();
    }
}

【问题讨论】:

  • Actions 没有返回值,请改用Func&lt;bool&gt;。虽然不清楚如果您立即阻止等待任务完成,使用Task.Run 会获得什么。
  • 动作是异步的。
  • @Will "The action is asynchronous" 更令人困惑的原因是在Task.Run之后立即同步等待...
  • 我认为@Will 缺少的是他没有意识到Task.Result 块。将,_currentTask.Result 块。
  • 该操作是对另一台计算机的更新。因此它是一个异步调用。但是在这个方法中我需要阻塞直到我收到返回值,它会告诉我更新是否成功。

标签: c# .net casting delegates task


【解决方案1】:

这个怎么样:

class Class1
{
    private static Queue<Func<bool>> _oisQueue = new Queue<Func<bool>>();

    private async Task<bool> RunNextTask()
    {
        bool success = true;

        if (_oisQueue.Any())
        {
            success = await Task.Run(_oisQueue.First());
            _oisQueue.Dequeue();
        }

        return success;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    相关资源
    最近更新 更多