c# - 在后台线程上运行 "async"方法

标签 c# windows-phone windows-phone-7.1 async-await

我正在尝试从普通方法运行“异步”方法:

public string Prop
{
    get { return _prop; }
    set
    {
        _prop = value;
        RaisePropertyChanged();
    }
}

private async Task<string> GetSomething()
{
    return await new Task<string>( () => {
        Thread.Sleep(2000);
        return "hello world";
    });
}

public void Activate()
{
    GetSomething.ContinueWith(task => Prop = task.Result).Start();
    // ^ exception here
}

抛出的异常是:

Start may not be called on a continuation task.

这到底是什么意思?我怎样才能简单地在后台线程上运行我的异步方法,将结果分派(dispatch)回 UI 线程?

编辑

还尝试了 Task.Wait,但等待永远不会结束:

public void Activate()
{
    Task.Factory.StartNew<string>( () => {
        var task = GetSomething();
        task.Wait();

        // ^ stuck here

        return task.Result;
    }).ContinueWith(task => {
        Prop = task.Result;
    }, TaskScheduler.FromCurrentSynchronizationContext());
    GetSomething.ContinueWith(task => Prop = task.Result).Start();
}

最佳答案

具体修复您的示例:

public void Activate()
{
    Task.Factory.StartNew(() =>
    {
        //executes in thread pool.
        return GetSomething(); // returns a Task.
    }) // returns a Task<Task>.
    .Unwrap() // "unwraps" the outer task, returning a proxy
              // for the inner one returned by GetSomething().
    .ContinueWith(task =>
    {
        // executes in UI thread.
        Prop = task.Result;
    }, TaskScheduler.FromCurrentSynchronizationContext());
}

这会起作用,但它是老式的。

在后台线程上运行某些东西并分派(dispatch)回 UI 线程的现代方法是使用 Task.Run()asyncawait:

async void Activate()
{
    Prop = await Task.Run(() => GetSomething());
}

Task.Run 将在线程池线程中启动一些东西。当您 await 某些东西时,它会自动返回启动它的执行上下文。在这种情况下,您的 UI 线程。

您通常不需要调用 Start()。首选 async 方法、Task.RunTask.Factory.StartNew -- 所有这些都会自动启动任务。使用 awaitContinueWith 创建的延续也会在其父级完成时自动启动。

关于c# - 在后台线程上运行 "async"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20304258/

相关文章:

c# - C#Windows Phone-结合音频和视频文件

Windows phone 7 新 Windows phone 8 操作系统版本中的应用程序

c# - 在 WinForms RichTextBox 中重置 RTF 格式而不丢弃其文本?

c# - WCF 中的泛型集合支持

c# - 什么是存储项目的 FolderRelativeId?

c# - 以编程方式设置 Segoe UI Symbol 字体

sockets - 使用套接字[Windows Phone]

c# - 让 WP7 上的 silverlight 应用全屏运行

c# - 覆盖文本和 OnKeyUp/OnKeyPress

c# - 更改机器人discordbot C#上的昵称