很抱歉,我肯定会变成一个非常愚蠢的问题。
在我的Xamarin应用程序中,我使用的是Android而不是Xamarin表单,但我想使用Activity.RunOnUIThread (来自Android),所有Device.BeginInvokeOnMainThread文档都建议使用Device.BeginInvokeOnMainThread(来自Xamarin.Forms)项目。显然,由于我没有关于xamarin.forms项目的参考,所以我没有这个工具。
如果我不想使用表单,在哪里可以找到Xamarin中的运行ui线程机制?
发布于 2016-04-14 09:54:10
Android:
Android Activity有一个可以使用的RunOnUiThread方法:
RunOnUiThread ( () => {
// manipulate UI controls
});参考文献:https://developer.xamarin.com/api/member/Android.App.Activity.RunOnUiThread/p/Java.Lang.IRunnable/
iOS:
InvokeOnMainThread (delegate {
// manipulate UI controls
});发布于 2016-04-14 10:12:39
如果您想通过您的PCL /共享代码和项目中的任何其他地方来执行此操作。你有两个选择。
跨平台方式,使用本机机制
然后您就可以从共享代码中调用
InvokeHelper.Invoke(() => DoSomething("bla"));完全跨平台方式
您也可以实现InvokeHelper跨平台。
public class InvokeHelper
{
// assuming the static initializer is executed on the UI Thread.
public static SynchronizationContext mainSyncronisationContext = SynchronizationContext.Current;
public static void Invoke(Action action)
{
mainSyncronisationContext?.Post(_ => action(), null);
}
}发布于 2016-04-14 09:50:11
这里有一个从正式文件获得的示例
public class ThreadDemo : Activity
{
TextView textview;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Create a new TextView and set it as our view
textview = new TextView (this);
textview.Text = "Working..";
SetContentView (textview);
ThreadPool.QueueUserWorkItem (o => SlowMethod ());
}
private void SlowMethod ()
{
Thread.Sleep (5000);
RunOnUiThread (() => textview.Text = "Method Complete");
}
}基本上,如果您想运行多行代码,可以这样做:
RunOnUiThread(()=>{
MethodOne();
MethodTwo();
});https://stackoverflow.com/questions/36619293
复制相似问题