.NET 2.0中后台线程在UI线程上的调用方法 [英] Call method on UI thread from background in .net 2.0

查看:60
本文介绍了.NET 2.0中后台线程在UI线程上的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MonoDevelop(.net 2.0)开发iOS和Android应用程序.我使用BeginGetResponse和EndGetResponse在后台线程中异步执行webrequest.

I am using MonoDevelop (.net 2.0) to develop a iOS and Android app. I use BeginGetResponse and EndGetResponse to asynchronously do a webrequest in a background thread.

IAsyncResult result = request.BeginGetResponse(new AsyncCallback(onLogin), state);

但是,回调onLogin似乎仍然在后台线程上运行,不允许我与UI进行交互.我该如何解决?

However, the callback onLogin does seem to still be running on a background thread, no allowing me to interact with the UI. How do I solve this?

可以看到有特定于Android和iOS的解决方案,但需要一个跨平台的解决方案.

Can see that there are Android and iOS specific solutions but want a cross-platform solution.

从mhutch答案中我可以理解到这一点:

From mhutch answer I've got this far:

IAsyncResult result = request.BeginGetResponse(o => {
            state.context.Post(() => { onLogin(o); });
        }, state);

状态包含类型为SynchronizationContext且设置为SynchronizationContext.Current

Where state contains a context variable of type SynchronizationContext set to SynchronizationContext.Current

它抱怨Post需要两个参数,第二个是Object state.插入state会显示错误

It complains that Post requires two arguments, the second one being Object state. Inserting state gives the error

Argument `#1' cannot convert `anonymous method' expression to type `System.Threading.SendOrPostCallback' (CS1503) (Core.Droid)

推荐答案

Xamarin.iOS和Xamarin.Android都为GUI线程设置了SynchronizationContext.

Both Xamarin.iOS and Xamarin.Android set a SynchronizationContext for the GUI thread.

这意味着您从GUI线程获取SynchronizationContext.Current并将其传递给回调(例如,通过状态对象或在lambda中捕获).然后,您可以使用上下文的Post方法在主线程上调用事物.

This means you get the SynchronizationContext.Current from the GUI thread and pass it to your callback (e.g via the state object or captured in a lambda). Then you can use the context's Post method to invoke things on the main thread.

例如:

//don't inline this into the callback, we need to get it from the GUI thread
var ctx = SynchronizationContext.Current;

IAsyncResult result = request.BeginGetResponse(o => {
    // calculate stuff on the background thread
    var loginInfo = GetLoginInfo (o);
    // send it to the GUI thread
    ctx.Post (_ => { ShowInGui (loginInfo); }, null);
}, state);

这篇关于.NET 2.0中后台线程在UI线程上的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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