0

我正在用 VB.NET 编写一个发送短信的应用程序。

您能否发布 此代码和/或指南的PYTHON->VB.NET翻译?

提前致谢!!!

import threading
class MessageThread(threading.Thread):
    def __init__(self,msg,no):
        threading.Thread.__init__(self)
        self.msg = msg  # text message
        self.no  = no   # mobile number
    def run(self):
        # function that sends "msg" to "no"
        send_msg(msg,no) 

# records of users are retrived from database 
# and (msg,no) tuples are generated
records = [(msg1,no1),(msg2, no2),...(msgN,noN)] 

thread_list = []

for each in records:
    t = MessageThread(each)
    thread_list.append(t)

for each in thread_list:
    each.start()

for each in thread_list:
    each.join()
4

2 回答 2

1

此代码为每个 msg/no 元组创建一个线程并调用 sendmsg。第一个“for each ... each.start()”启动线程(仅调用 sendmsg),第二个“for each ... each.join()”等待每个线程完成。根据记录的数量,这可能会创建大量线程(如果您发送 1000 条 SMS 记录会怎样),尽管它是异步的,但不一定有效。

代码相对简单且 Pythonic,而对于 .NET,您可能希望使用ThreadPoolBackgroundWorker来执行 sendmsg 调用。您将需要创建一个等效于元组 (msg,no) 的 .NET 类,并且可能将 sendmsg() 函数放在类本身中。然后创建 .NET 代码以加载消息(Python 代码中未显示)。通常,您也会使用通用 List<> 来保存 SMS 记录。然后 ThreadPool 会将所有项目排队并调用 sendmsg。

如果您试图保持代码与原始 Python 相同,那么您应该查看IronPython

(sendmsg 中的下划线导致文本使用斜体,所以我在回复中删除了下划线。)

于 2009-05-15T19:00:01.053 回答
0

这是 IronPython 代码(“Python for .NET”),因此源代码使用 .NET 框架,就像 VB 一样,所有类(甚至System.Threading.Thread)都可以以与所示相同的方式使用。

一些技巧:

MessageThread派生自Threadmsg并且no必须声明为类变量,__init__是构造函数,self成员函数中的 -parameter 不会转码为 VB(只需将其省略)。使用List<Thread>forthread_list并为 中的元组定义一个小结构records

于 2009-05-15T18:31:12.480 回答