使用线程异步执行C#方法
我在一个类中有一个方法,需要异步执行两次。 该类有一个接受URL作为参数的构造函数:使用线程异步执行C#方法,c#,multithreading,C#,Multithreading,我在一个类中有一个方法,需要异步执行两次。 该类有一个接受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 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();
是这样吗?有人能帮忙吗?您需要更改
ThreadStart
创建,以将该方法用作目标,而不是调用该方法
Thread oThread = new Thread(new ThreadStart(abc.Read);
注意我是如何使用
abc.Read
而不是abc.Read()
。此版本导致ThreadStart
委托指向方法abc.Read
。原始版本abc.Read()
正在立即调用Read
方法,并试图将结果转换为ThreadStart
委托。这可能不是您想要的删除括号以创建代理:
Thread oThread = new Thread(new ThreadStart(abc.Read));
并对oThread1
执行相同的操作。这是。您也可以这样做:
Thread oThread1 = new Thread(() => abc1.Read());
您可以将lambda传入线程
构造函数,而不是新建一个线程开始
对象
约瑟夫·阿尔巴哈里(Joseph Albahari)对线程有很好的理解。非常容易阅读,并且有很多例子。如果适合您,您也可以尝试BackgroundWorker。。如何将参数URL传递给构造函数?@srikanth:看起来您已经在这样做了
abc。Read
仍然可以正确地引用此。我需要为abc类的每个实例发送两个不同的URL。@srikanth:下面是一个演示:您是否存储传递给构造函数的URL?只需像往常一样使用此
访问即可…收到了,非常感谢。我可以使用不同的url同时执行Read方法。很好用。它会在prod中产生任何问题吗?@JaredPar。。如何将参数URL传递给ABC类的构造函数?我需要为ABC类的每个实例发送两个不同的URL。@srikanth您是否试图在后台线程上创建实例?r。。。我想出来了。否则,我的代码工作正常。。使用不同的url异步执行Read()方法。这是线程安全的吗?一旦我们转到Prod,它会产生任何问题吗?