【发布时间】:2011-09-15 12:18:06
【问题描述】:
您可能知道,Android 的 SDK 具有一个 AsyncTask 类,它允许在单独的线程上执行代码并在主 (UI) 线程中获取结果。简而言之,是这样的:
class AsyncTask
{
void onPreExecute(...)
{
//Executed on the main thread BEFORE the secondary thread gets to work on anything.
}
void execute(...)
{
//This runs on the secondary thread.
}
void onPostExecute(...)
{
//This runs on the main thread AFTER the secondary thread finishes work. You get the result here in the form of some data type.
}
}
当然,这只是一个粗略的方案,但如果您不熟悉它,它应该提供有关 AsyncTask 的足够信息。基本上,我在 Microsoft 的 .NET Framework 中寻找相同的功能。
在我开始编写自己的类来执行此操作之前,我想确定没有任何东西可以让我在框架中获得所需的结果。我正在使用.NET 4.0。也许某种“聪明”的 System.Threading.Tasks.Task 使用?不知道,我把这个留给你。
简而言之,我想将一些输入传递给一个函数,在辅助线程上运行代码,并在完成时通过主线程更新一些 UI 元素。锁定主线程(例如通过Task.Wait())不能很好地满足我的要求。
【问题讨论】: