使用线程异步执行C#方法

3

我有一个类里面的方法需要异步执行两次。该类有一个构造函数,接受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();

这是它的工作方式吗?有人可以帮忙吗?


如果适合您,您也可以尝试使用BackgroundWorker。 - Afnan Bashir
3个回答

3

您需要更改ThreadStart的创建方式,使用该方法作为目标而不是调用该方法。

Thread oThread = new Thread(new ThreadStart(abc.Read);

请注意我使用了abc.Read而不是abc.Read()。这个版本使得ThreadStart委托指向方法abc.Read。原始版本abc.Read()立即调用了Read方法,并试图将结果转换为ThreadStart委托。这可能不是您想要的。

@JaredPar.. 你好,请问如何将URL参数传递给ABC类的构造函数?我需要为每个ABC类实例发送两个不同的URL。 - srikanth
@srikanth 你是在后台线程上创建实例吗? - JaredPar
我想通了。否则,我的代码正常工作... 异步执行不同 URL 的 Read() 方法。这是线程安全的吗?一旦我们移动到生产环境,它会创建任何问题吗? - srikanth

3

取消括号以创建委托:

Thread oThread = new Thread(new ThreadStart(abc.Read));

对于 oThread1,也同样如此。这是MSDN的委托教程


谢谢Minitech。你如何将参数URL传递给构造函数? - srikanth
我需要为ABC类的每个实例发送两个不同的URL。 - srikanth
1
@srikanth:这是一个演示:http://ideone.com/OVMpA。你有把你传递给构造函数的URL存储下来吗?像平常一样使用`this`访问它即可... - Ry-
@srikanth:不会死锁,除非你正在访问共享资源。Thread.Join 在正确的位置将等待线程,而在错误的位置将导致死锁。 - Ry-
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/7037/discussion-between-srikanth-and-minitech - srikanth
显示剩余3条评论

1

你也可以这样做:

Thread oThread1 = new Thread(() => abc1.Read());

你可以在Thread构造函数中传递一个lambda表达式,而不是创建一个新的ThreadStart对象。
Joseph Albahari有一份很棒的关于多线程的在线资源。非常容易阅读,而且有很多示例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接