我在类中有一个方法,我需要异步执行两次。 该类有一个构造函数,它接受URL作为参数:
ABC abc= new ABC(Url);
// Create the thread object, passing in the abc.Read() method
// via a ThreadStart delegate. This does not start the thread.
Thread oThread = new Thread(new ThreadStart(abc.Read());
ABC abc1= new ABC(Url2)
// Create the thread object, passing in the abc.Read() method
// via a ThreadStart delegate. This does not start the thread.
Thread oThread1 = new Thread(new ThreadStart(abc1.Read());
// Start the thread
oThread.Start();
// Start the thread
oThread1.Start();
这是它的工作方式吗?有人可以帮忙吗?
答案 0 :(得分:3)
您需要更改ThreadStart
创建以将方法用作目标,而不是调用方法
Thread oThread = new Thread(new ThreadStart(abc.Read);
请注意我使用abc.Read
代替abc.Read()
的方法。此版本会导致ThreadStart
委托指向方法abc.Read
。原始版本abc.Read()
立即调用Read
方法并尝试将结果转换为ThreadStart
委托。这可能不是你想要的
答案 1 :(得分:3)
删除括号以创建委托:
Thread oThread = new Thread(new ThreadStart(abc.Read));
为oThread1
做同样的事情。这是MSDN's Delegates Tutorial。
答案 2 :(得分:1)
你也可以这样做:
Thread oThread1 = new Thread(() => abc1.Read());
您可以将lambda传递给Thread
构造函数,而不是新建一个新的ThreadStart
对象。
约瑟夫·阿尔巴哈里(Joseph Albahari)对线程有很好的online resource。非常容易阅读和许多例子。