[英]How to wrap untied callback to asynchronous function
I have to use external component which consist of setting callback "onReceiveData" first to a single method. 我必须使用外部组件,该组件首先将回调“ onReceiveData”设置为单个方法。 Then whenever I call sendData I process result in setted method.
然后,每当我调用sendData时,我都会使用setted方法处理结果。 I'm come from javascript world and I am very confused how to process such request in MVC controller where I need to call the function, wait for response and return results in View.
我来自javascript世界,我很困惑如何在MVC控制器中处理此类请求,我需要在其中调用函数,等待响应并在View中返回结果。 Is there some easy way to wrap it to asynchronous method to use async/await?
有一些简单的方法可以将其包装为异步方法以使用async / await吗?
var component = new Component();
component.Server = "10.0.0.1:30";
component.RecvData = new Component.RecvDataCB(someMethod);
component.start();
component.SendDate(data);
It would be nice to see whole context but for now I'm not sure what you are looking for. 看到整个上下文会很高兴,但是现在我不确定您在寻找什么。 I see two questions ( maybe even three ).
我看到两个问题(甚至三个)。
Let's begin. 让我们开始。
@Model
and name @Model
和名称 Controller: 控制器:
public class HomeController : Controller
{
public IActionResult Index()
{
var model = new UserViewModel();
return View(model);
}
}
ViewModel: ViewModel:
public class UserViewModel
{
public string Name { get; set; }
public int Age { get; set; }
}
View: 视图:
@model UserViewModel
<div class="text-center">
<p>@Model.Name</p>
<p>@Model.Age</p>
</div>
async
the return type of method should be Task<T>
. async
则方法的返回类型应为Task<T>
。 So let's image you have class( same ViewModel. NOTICE never ever keep business logic in viewModel. ) but instead just properties you have some methods inside. ViewModel: ViewModel:
public class UserViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public UserViewModel(int age, string name)
{
this.Age = age;
this.Name = name;
}
public async Task<int> GetAge()
{
return this.Age;
}
public async Task<string> GetName()
{
return this.Name;
}
}
Since your methods' return type is Task they can be async
and await
'ed. 由于方法的返回类型为Task,因此它们可以
async
并await
。 You controller would look like this. 您的控制器将如下所示。
Controller: 控制器:
public class HomeController : Controller
{
public async Task<IActionResult> Index()
{
var model = new UserViewModel(16,"Bob");
string name = await model.GetName();
int age = await model.GetAge();
return View(model);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.