【问题标题】:Assigning variables from async method从异步方法分配变量
【发布时间】:2015-11-19 22:38:14
【问题描述】:

我无法调用我的异步方法...我想调用该方法,以便可以使用该方法内部变量中的值。 注意ViewDetailsAsync 来自网络服务。

这就是我所拥有的:

namespace TilesAndNotifications.Models
{
public class PrimaryTile
{
    public async void GetTileData()
    {
        ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
        string name= string.Empty;
        string description = string.Empty;
        string type= string.Empty;

        var res = await client.ViewDetailsAsync();

        name= res.NameView;
        description = res.DescriptionView;
        type= res.TypeView;
    }

    public string CurrentName { get; set; } = "John Doe";
    public string CurrentDescription { get; set; } = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.";
    public string CurrentType { get; set; } = "Employee";
}
}

我想完成什么

public string CurrentName { get; set; } = GetTileData.name;
public string CurrentDescription { get; set; } = GetTileData.description
public string CurrentType { get; set; } = GetTileData.type;

但我不确定从异步方法中获取该信息...我知道这可能是初级的,但我似乎无法得到它。

【问题讨论】:

  • 来自“public async void GetTileDate()”....
  • Never do async void 除非您正在编写事件处理程序。
  • 你让每个人都感到困惑。您之前的帖子有一个 xml 文档。这个帖子的人不知道。此外,您之前发布的 xml 没有 3 个属性 CurrentName、CurrentDescription 和 CurrentType。请发布包含这三个属性的正确 XML。
  • 因为我改了,所以新问题

标签: c# wcf asynchronous


【解决方案1】:

您可以通过async 方法很好地设置属性:

public async Task GetTileDataAsync()
{
  ...
  var res = await client.ViewDetailsAsync();

  CurrentName = res.NameView;
  CurrentDescription = res.DescriptionView;
  CurrentType = res.TypeView;
}

当然,调用代码必须先awaitGetTileDataAsync 返回的任务才能使用这些属性。

【讨论】:

  • 好的,所以我已将它们分配给我的变量。如何调用 GetTileDataAsyn() 方法?让它真正执行?
  • @代码:await obj.GetTileDataAsync();
【解决方案2】:

您不能使用属性默认值来执行此操作,并且由于类构造不是异步的,因此除非您实现同步等待,否则您将无法在构造函数上执行此操作:

public PrimaryTile()
{
     var titleData = GetTitleData().Result;
}

无论如何,这是一个非常非常非常糟糕的主意,因为如果您不非常小心地实现异步/线程代码,它可能会在某些情况下产生死锁强>。

您可能需要重新考虑您的架构并制定更好的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多