簡體   English   中英

使用線程異步執行C#方法

[英]execute a C# method asynchronously using Threading

我在類中有一個方法,我需要異步執行兩次。 該類有一個構造函數,它接受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做同樣的oThread1 這是MSDN的代表教程

你也可以這樣做:

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

您可以將lambda傳遞給Thread構造函數,而不是新建一個新的ThreadStart對象。

約瑟夫·阿爾巴哈里(Joseph Albahari)擁有關於線程的強大在線資 很容易閱讀和很多例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM