Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用线程异步执行C#方法_C#_Multithreading - Fatal编程技术网

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

使用线程异步执行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());

我在一个类中有一个方法,需要异步执行两次。 该类有一个接受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();

是这样吗?有人能帮忙吗?

您需要更改
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,它会产生任何问题吗?