[英]Threading A Method Contained In An Object - C#
我正在編寫一個程序,它將分析股票市場的變化。
每當股票圖表上的蠟燭更新時,我的算法都會在每個圖表上掃描某些數據。 我注意到該過程每次大約花費0.6秒,凍結了我的應用程序。 它不會陷入循環中,並且沒有其他問題,例如異常錯誤會使它變慢。 只需要一點時間。
為了解決這個問題,我試圖查看是否可以對算法進行線程化。
為了調用該算法來檢查圖表,我必須調用它:
checkCharts.RunAlgo();
由於線程需要一個對象,因此我試圖找出如何運行RunAlgo()的方法,但是我沒有任何運氣。
如何讓線程在我的checkCharts對象中運行此方法? 由於數據向后傳播,因此無法啟動新的checkCharts對象。 我必須從現有對象中繼續使用該方法。
編輯:
我嘗試了這個:
M4.ALProj.BotMain checkCharts = new ALProj.BotMain();
Thread algoThread = new Thread(checkCharts.RunAlgo);
它告訴我,checkCharts.RunAlgo的checkCharts一部分給我,“ 是必需的非靜態字段,方法或屬性的對象引用‘M4.ALProj.BotMain’。”
在一個特定的if語句中,我將放置algoThread.Start();。 知道我在那里做錯了嗎?
您的問題的答案實際上非常簡單:
Thread myThread = new Thread(checkCharts.RunAlgo);
myThread.Start();
但是,更復雜的部分是確保方法RunAlgo
訪問checkCharts對象內部的變量時,這是以線程安全的方式發生的。
有關如何同步從多個線程對數據的訪問的幫助,請參閱線程同步 。
我寧願使用Task.Run
而不是Thread
。 Task.Run
利用已優化的ThreadPool
來有效處理各種負載。 您還將獲得Task
所有好處。
await Task.Run(()=> checkCharts.RunAlgo);
試試這個代碼塊。 它是一個基本的樣板,但是您可以輕松構建並擴展它。
//If M4.ALProj.BotMain needs to be recreated for each run then comment this line and uncomment the one in DoRunParallel()
private static M4.ALProj.BotMain checkCharts = new M4.ALProj.BotMain();
private static object SyncRoot = new object();
private static System.Threading.Thread algoThread = null;
private static bool ReRunOnComplete = false;
public static void RunParallel()
{
lock (SyncRoot)
{
if (algoThread == null)
{
System.Threading.ThreadStart TS = new System.Threading.ThreadStart(DoRunParallel);
algoThread = new System.Threading.Thread(TS);
}
else
{
//Recieved a recalc call while still calculating
ReRunOnComplete = true;
}
}
}
public static void DoRunParallel()
{
bool ReRun = false;
try
{
//If M4.ALProj.BotMain needs to be recreated for each run then uncomment this line and comment private static version above
//M4.ALProj.BotMain checkCharts = new M4.ALProj.BotMain();
checkCharts.RunAlgo();
}
finally
{
lock (SyncRoot)
{
algoThread = null;
ReRun = ReRunOnComplete;
ReRunOnComplete = false;
}
}
if (ReRun)
{
RunParallel();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.