我有一個用戶界面,一個自定義類和一個線程。我想在一個單獨的線程中完全運行自定義類。有沒有一種乾淨的方式來做到這一點?如何在單獨的線程中執行自定義類的方法調用?
例如。在下面的MainForm中,當UI調用_threadOneClass.Sleep時,我需要UI去到產生的ThreadOne並調用ThreadOne中的Sleep方法,而不是在主線程中。
基本上,MyClass中的所有方法調用都需要在ThreadOne中執行,而不是在主線程中執行。這就像MyClass在它自己的「進程」上運行,同時仍然可以從MainForm調用。
MainForm有3個按鈕和1個用於記錄的文本框。
我正在考慮派生Thread類,但它是密封的。因此,對每個微軟來說,推導絕對是一種錯誤的方式
幫助親愛的專家?
這裏是輸出(MainThread ID = 10,ID ThreadOne = 11)
MyClass instantiated Starting ThreadOne 11-Run.start Sleeping ThreadOne 10-Run.sleep for 3000 'Need this to run on ThreadID 11 10-Run.woke up 'Need this to run on ThreadID 11 Stopping ThreadOne 11-Run.done
下面是如何代碼看起來象。
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private Thread _threadOneThread;
private MyClass _threadOneClass;
private void btnThreadOneCreate_Click(object sender, EventArgs e)
{
_threadOneClass = new MyClass(this);
_threadOneThread = new Thread(new ThreadStart(_threadOneClass.Run));
_threadOneThread.Start();
}
private void btnThreadOneStop_Click(object sender, EventArgs e)
{
_threadOneClass.IsRunning = false;
}
private void btnThreadOneSleep_Click(object sender, EventArgs e)
{
_threadOneClass.Sleep(3000);
}
public void Log(string txt)
{
MainForm.SetText(txtLog, txt);
}
internal static void SetText(Control ctl, string val)
{
if (ctl.InvokeRequired)
ctl.Invoke((MethodInvoker)delegate() { ctl.Text += Environment.NewLine + val; });
else
ctl.Text += Environment.NewLine + val;
}
}
class MyClass
{
public MyClass(MainForm frm)
{
_mainForm = frm;
}
private MainForm _mainForm;
public bool IsRunning = true;
public void Run()
{
_mainForm.Log(Thread.CurrentThread.ManagedThreadId.ToString() + "-Run.start");
while (IsRunning) { }
_mainForm.Log(Thread.CurrentThread.ManagedThreadId.ToString() + "-Run.done");
}
public void Sleep(int milliseconds)
{
_mainForm.Log(Thread.CurrentThread.ManagedThreadId.ToString() + "-Run.sleep for " + milliseconds.ToString());
Thread.Sleep(milliseconds);
_mainForm.Log(Thread.CurrentThread.ManagedThreadId.ToString() + "-Run.woke up");
}
}
爲什麼你需要一個專用線程?你不能使用標準的Begin/End委託調用模式嗎? – cdhowie
不是。這是一個複雜的場景,但基本上我正在爲我的C#winform調用一個單獨的進程打包。這個單獨的過程是專用和獨立運行的,所以我需要使這個包裝專用。沒有線程,我的C#winform很容易卡住.. –