在 windows phone 8 中的同步方法中调用异步方法 [英] call async methods in synchronized method in windows phone 8

查看:26
本文介绍了在 windows phone 8 中的同步方法中调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在同步方法中调用异步方法的更好方法吗.

is this a better way to call a async method in a synchronised method.

public bool Sync() 
{ 
  return Task.Run(() => MyClass.IsSyncDone()).Result; 
}

会导致死锁吗?我真的需要知道更好的方法.因为我不想异步到系统调用,即应用程序启动、注册方法等.任何人都可以帮忙.

will it cause deadlocks? I really need to know a better way. because I do not want to make async to system calls i.e. App launching, registered methods etc. can anyone please help.

推荐答案

如果您不需要回复,那么您可以轻松地执行以下操作:

If you didn't need the responses then you could easily do something like this:

public bool Sync() 
{ 
    Task.Run(async () => await MyClass.DoSync());
}

您需要响应意味着更复杂的代码.如果没有看到完整代码,很难提供具体示例,但通常最好不要将这种长时间运行、复杂的异步操作与同步操作联系起来.
要么将延续传递给异步方法以通过任务创建,要么让异步方法在完成或触发自定义事件时更新视图模型的绑定属性.

That you need the response will mean more complicated code. Without seeing the full code it's hard to provide specific examples but it's generally better to not tie such long running, complicated asynchronous operations to synchronous ones.
Either pass a continuation to the async method to create via a task or have the async method update a bound property of a viewmodel when finished or fire a custom event.

重要的是不要在应用程序生命周期事件处理程序中执行任何可能长时间运行的异步操作,因为这些操作可能会导致应用程序被强制终止或应用程序数据处于不一致状态.

It is important not to perform any potentially long running async operations in the application livecycle event handlers as if these take to long it can lead to the application being forcefully terminated or the app data being left in an inconsistent state.

这篇关于在 windows phone 8 中的同步方法中调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆