如何使用BeginInvoke C#

Moh*_*din 46 c# begininvoke

你能解释一下吗:

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表达式并提供预期TypeInvoke()

Invoke导致说Action在要创建Control的窗口句柄的线程上执行.通常需要更改线程以避免Exceptions.例如,如果尝试在需要Invoke时设置Rtf属性RichTextBox,而不先调用Invoke,Cross-thread operation not valid则会抛出异常.Control.InvokeRequired在调用Invoke之前检查.

BeginInvoke是异步版本Invoke.异步意味着线程不会阻塞调用者,而不是阻塞的同步调用.

  • @KyleBaran - "Action"与线程安全无关,即"Invoke".`Invoke`接受`Delegate`作为参数.所以任何可转换为`Delegate`的东西都可以作为参数传递. (4认同)

Pav*_*nin 10

我想你的代码与Windows Forms有关.如果需要在UI线程中异步执行某些操作,则
调用BeginInvoke:在大多数情况下更改控件的属性.
粗略地说,这是通过将委托传递给定期执行的某个过程来实现的.(消息循环处理和类似的东西)

如果BeginInvokeDelegate类型调用,则只是异步调用委托.
(Invoke用于同步版本.)

如果你想要更多适用于WPF和WinForms的通用代码,你可以考虑使用任务并行库并运行Task带有相应的上下文.(TaskScheduler.FromCurrentSynchronizationContext())

并添加一些已经被别人说过的内容:Lambdas可以被视为匿名方法或表达式.
这就是为什么你不能只使用varlambdas:编译器需要一个提示.

更新:

这需要.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()将阻止调用线程直到任务结束.

阅读更多有关任务的信息.