开发者

Do you like this idea? (About threads)

开发者 https://www.devze.com 2022-12-21 10:06 出处:网络
Would it not be nice to be able to start a thread like this. Sub DoStuff() Using MyThead = New Threading.Thread()

Would it not be nice to be able to start a thread like this.

Sub DoStuff()
    Using MyThead = New Threading.Thread()
       'Do stuff on MyThread.
 开发者_JS百科   End Using
End Sub

It is much less code to write and looks nicer than:

Sub DoStuff()
    Dim MyThread As New Threading.Thread(AddressOf DoStuffThread)
    MyThread.Start()
End Sub

Sub DoStuffThread()
    'Do Stuff
End Sub


This is already possible (with a bit more noise) in C# using anonymous delegates:

new Thread(() => {
  // do stuff on thread
}).Start();

and will be supported in VB 10 via multiline lambdas:

New Thread(Sub()
             ' do stuff on thread
           End Sub).Start()

(I may have the VB syntax wrong, I haven't really played with VB 10.)


So in your example ... a thread would be created that contained the code down to the End Using and begin execution in parallel?

No, I don't like that at all, it's much, much less clear what's happening. If you imagine it working differently please update your question to describe your concept.


When does the code after End Using run? Does it wait until the thread finished, or does the Using block return immediately? If it waits until the thread finishes, then what's the point of launching a thread at all? But if it doesn't wait, then what do you do if you want to get the thread's return value?

There do exist more elegant idioms for threads than the standard one that you mention. In C#, for example, you can use an anonymous delegate to do much the same thing, and C# 4.0 has a variety of threading-related tools. But your example does not illustrate one of them.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号