1. 實現非ui執行緒更新ui執行緒的**之前的基本做法是使用invoke實現,這裡採用的是 .net 4.0中的task來實現,**如下:2. 編碼中出現的乙個錯誤及**
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.threading.tasks;
using system.threading;
public partial class form1 : form
private cancellationtokensource cts;
private taskscheduler context = taskscheduler.current;
// 計算
private int32 sum(cancellationtoken token, int32 n)
return sum; }
protected override void onmouseclick(mouseeventargs e)
else
base.onmouseclick(e); }
} }最初的**將m_synccontextscheduler物件是通過下面的語句產生的:
private readonly taskscheduler m_synccontextscheduler =
taskscheduler.fromcurrentsynchronizationcontext();
debug時,產生如下錯誤:
通過異常資訊可以看出這可能是當前初始化還為完成,那麼這就引出c#中建構函式初始化和屬性的初始化順序的問題,通過除錯或者是檢視生成的il**發現了問題所在,c#中首先執行
private taskscheduler m_synccontextscheduler =
taskscheduler.fromcurrentsynchronizationcontext();
此時環境還沒有初始話完成。il中更加明顯:
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed {
// code size 87 (0x57)
.maxstack 2
il_0000: ldarg.0
il_0001: ldnull
il_0007: ldarg.0
il_0008: call class [mscorlib]system.threading.tasks.taskscheduler [mscorlib]system.threading.tasks.taskscheduler::fromcurrentsynchronizationcontext()
il_0012: ldarg.0
il_0013: call class [mscorlib]system.threading.tasks.taskscheduler [mscorlib]system.threading.tasks.taskscheduler::get_current()
il_001d: ldarg.0
// 初始化,呼叫form建構函式
il_001e: call instance void [system.windows.forms]system.windows.forms.form::.ctor()
UI執行緒和非UI執行緒的互動方式
一般應該把像讀寫檔案 請求網路這類的耗時操作放在子執行緒中去執行,這樣可以避免ui執行緒的響應事件過慢,但是很多情況下在子執行緒中需要更新介面,比如從網路中獲取到或者響應字串後,將結果顯示到介面上,但是在子執行緒中不允許直接更新ui介面,這時就需要在子執行緒中將結果返回給ui執行緒,由ui執行緒來負...
Android在非UI執行緒中更新UI的方法
在ui thread中建立handler。用sendmessage message 或者obtainmessage result,obj sendtotarget 在handlemessage方法中更新ui。推薦使用obtainmessage result,obj sendtotarget 由於這種...
子執行緒更新UI
一般在winform c s程式中經常會在子執行緒中更新控制項的情況,桌面程式ui執行緒是主線程,當試圖從子執行緒直接修改控制項屬性時會出現 從不是建立控制項的執行緒訪問它 的異常提示。跨執行緒更新ui控制項的常用方法有兩種 1.使用控制項自身的invoke begininvoke方法 2.使用sy...