簡體   English   中英

什么是 Dispatcher.PushFrame 的 Xamarin Forms 等效項?

[英]What is the Xamarin Forms equivalent of Dispatcher.PushFrame?

我在我的 WPF 應用程序中有以下代碼來調用和等待來自 UI 線程上的非異步 function 的異步函數而不阻塞它。 這是通過使用 DispatcherFrame 在后台發送消息來完成的:

public static void WaitWithPumping(this Task task)
{
    if (task == null) throw new ArgumentNullException(“task”);
    var nestedFrame = new DispatcherFrame();
    task.ContinueWith(_ => nestedFrame.Continue = false);
    Dispatcher.PushFrame(nestedFrame);
    task.Wait();
}


public static T ResultWithPumping<T>(this Task<T> task)
{
    if (task == null) throw new ArgumentNullException(“task”);
    var nestedFrame = new DispatcherFrame();
    task.ContinueWith(_ => nestedFrame.Continue = false);
    Dispatcher.PushFrame(nestedFrame);
    return task.Result;
}

資源

我想在我的 Xamarin Forms iOS/Android 應用程序中使用類似的東西,以便能夠使用相同的代碼庫。

這都是必需的,因為 3rdparty 庫不支持 async/await。 出於同樣的原因,我不能只使用 Task.Run() 或 ConfigureAwait(false),因為這些函數需要在 UI 踏板上運行,並且我需要等待結果,然后再從同一個阻塞 function 啟動下一個任務。

public async void RunTaskOnUi1Async()
{
  await ProcessAsync();

  UpdateUiInner();
}

public async object RunTaskOnUi2Async()
{
  var result = await ProcessAsync();

  UpdateUiInner(result);
  return result;
}

// Called from the UI thread
public void RunTasks()
{
    UpdateUi();

    RunTaskOnUi1Async().WaitWithPumping();

    UpdateUi();

    var result = RunTaskOnUi2Async().ResultWithPumping();

    UpdateUi(result);
}

編輯#1:更新示例。 我知道這個例子有點蹩腳。 為什么我不將 RunTasks 更改為異步? 或者只是在后台線程上運行 ProcessAsync() ? 好吧,我正在處理一個遺留項目(當然),RunTasks 是一個 LUA 腳本處理引擎,它調用我的 C# 代碼並直接操作 UI,因此它必須在 UI 線程上運行,並且它在設計上是非異步的。 改變它將是一項巨大的工作。 但是我的代碼的 rest 是異步的,我可以通過使用消息泵送方法輕松解決 WPF 中的這個問題。

試試下面的代碼:

public static Task<T> BeginInvokeOnMainThreadAsync<T>(Func<T> a)
{
var tcs = new TaskCompletionSource<T>();
Device.BeginInvokeOnMainThread(() =>
    {
        try
        {
            var result = a();
            tcs.SetResult(result);
        }
        catch (Exception ex)
        {
            tcs.SetException(ex);
        }
    });
return tcs.Task;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM