你能解释一下吗:
someformobj.BeginInvoke((Action)(() =>
{
someformobj.listBox1.SelectedIndex = 0;
}));
Run Code Online (Sandbox Code Playgroud)
你能告诉我怎么才能begininvoke
准确使用?什么是Action
类型?为什么有空白括号()
?这意味着=>
什么?
P.B*_*key 76
Action
是.NET框架提供的委托类型.在Action
没有参数的方法分,不返回值.
() =>
是lambda表达式语法.Lambda表达式不是Type Delegate
.Invoke需要Delegate
这样Action
可以用来包装lambda表达式并提供预期Type
的Invoke()
Invoke
导致说Action
在要创建Control的窗口句柄的线程上执行.通常需要更改线程以避免Exceptions
.例如,如果尝试在需要Invoke时设置Rtf
属性RichTextBox
,而不先调用Invoke,Cross-thread operation not valid
则会抛出异常.Control.InvokeRequired
在调用Invoke之前检查.
BeginInvoke
是异步版本Invoke
.异步意味着线程不会阻塞调用者,而不是阻塞的同步调用.
Pav*_*nin 10
我想你的代码与Windows Forms有关.如果需要在UI线程中异步执行某些操作,则
调用BeginInvoke
:在大多数情况下更改控件的属性.
粗略地说,这是通过将委托传递给定期执行的某个过程来实现的.(消息循环处理和类似的东西)
如果BeginInvoke
为Delegate
类型调用,则只是异步调用委托.
(Invoke
用于同步版本.)
如果你想要更多适用于WPF和WinForms的通用代码,你可以考虑使用任务并行库并运行Task
带有相应的上下文.(TaskScheduler.FromCurrentSynchronizationContext()
)
并添加一些已经被别人说过的内容:Lambdas可以被视为匿名方法或表达式.
这就是为什么你不能只使用var
lambdas:编译器需要一个提示.
更新:
这需要.Net v4.0及更高版本
// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);
// also can be called anywhere. Task will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked)
task.Start(scheduler);
Run Code Online (Sandbox Code Playgroud)
如果你从其他线程启动任务并需要等待它的completition task.Wait()
将阻止调用线程直到任务结束.
阅读更多有关任务的信息.
归档时间: |
|
查看次数: |
112693 次 |
最近记录: |