.NET 2.0中后台线程在UI线程上的调用方法 [英] Call method on UI thread from background in .net 2.0
问题描述
我正在使用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屋!