Just wondering what the difference between BeginInvoke() and Invoke() are?

Mainly what each one would be used for.

EDIT: What is the difference between creating a threading object and calling invoke on that and just calling BeginInvoke() on a delegate? or are they the same thing?

推荐答案

Do you mean Delegate.Invoke/BeginInvoke or Control.Invoke/BeginInvoke?

  • Delegate.Invoke: Executes synchronously, on the same thread.
  • Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

Tim's answer mentions when you might want to use BeginInvoke - although it was mostly geared towards Delegate.BeginInvoke, I suspect.

For Windows Forms apps, I would suggest that you should usually use BeginInvoke. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person with FirstName and LastName properties, and you did:

person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";

Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)

Unless you have this sort of issue, however, Control.BeginInvoke is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke in a "fire and forget" manner - i.e. without ever calling EndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.

.net相关问答推荐

为什么Linq中的运算符逻辑不匹配结果,当值为0或在VB. NET中没有

为什么DotNet新的webapi;命令会为我生成不同的文件夹

SeriLog LogConext.PushProperty在ASP.NET MVC 5中不能使用OWIN中间件

如何将 signalR 添加到不同项目中的后台服务?

等待时 Blazor 服务器按钮刷新

如何正确使用await using语法?

双精度的 C++ 和 C# 十六进制值之间的差异

每 X 秒执行一次指定函数

.NET 4.0 中有内置的二叉搜索树吗?

File.ReadAllLines() 和 File.ReadAllText() 有什么区别?

OpenCV的.Net(dotNet)包装器?

在 Moq Callback() 调用中设置变量值

获取 .NET Framework 目录路径

属性应该与其类型同名吗?

支持 HTTPS 的 Httplistener

将接收到的对象转换为 List 或 IEnumerable

寻找 .NET 的命令行参数解析器

System.Speech.Recognition 和 Microsoft.Speech.Recognition 有什么区别?

将字典值转换为数组

IEnumerable vs IReadonlyCollection vs ReadonlyCollection 用于公开列表成员