当前位置: 动力学知识库 > 问答 > 编程问答 >

.net - Do you like this idea? (About threads)

问题描述:

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.

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: