簡體   English   中英

從C#中的其他類實例化線程方法

[英]Instantiating thread method from a different class in c#

有人可以指出我如何處理以下問題嗎? 基本上,我試圖重用以下示例中的代碼: http : //www.codeproject.com/KB/threads/SynchronizationContext.aspx我唯一不了解的問題是如何實例化RUN方法(如果在其中找到)不同的階級。 請參見以下代碼。

public partial class Form1 : Form
{
public Form1()
{
    InitializeComponent();
}

private void mToolStripButtonThreads_Click(object sender, EventArgs e)
{
    // let's see the thread id
    int id = Thread.CurrentThread.ManagedThreadId;
    Trace.WriteLine("mToolStripButtonThreads_Click thread: " + id);

    // grab the sync context associated to this
    // thread (the UI thread), and save it in uiContext
    // note that this context is set by the UI thread
    // during Form creation (outside of your control)
    // also note, that not every thread has a sync context attached to it.
    SynchronizationContext uiContext = SynchronizationContext.Current;

    // create a thread and associate it to the run method
    Thread thread = new Thread(Run);

    // start the thread, and pass it the UI context,
    // so this thread will be able to update the UI
    // from within the thread
    thread.Start(uiContext);
}


// THIS METHOD SHOULD GO IN A DIFFERENT CLASS (CLASS2) SO HOW TO CALL METHOD UpdateUI()
private void Run(object state)
{
    // lets see the thread id
    int id = Thread.CurrentThread.ManagedThreadId;
    Trace.WriteLine("Run thread: " + id);

    // grab the context from the state
    SynchronizationContext uiContext = state as SynchronizationContext;

    for (int i = 0; i < 1000; i++)
    {
        // normally you would do some code here
        // to grab items from the database. or some long
        // computation
        Thread.Sleep(10);

        // use the ui context to execute the UpdateUI method,
        // this insure that the UpdateUI method will run on the UI thread.

        uiContext.Post(UpdateUI, "line " + i.ToString());
    }
}

/// <summary>
/// This method is executed on the main UI thread.
/// </summary>
private void UpdateUI(object state)
{
    int id = Thread.CurrentThread.ManagedThreadId;
    Trace.WriteLine("UpdateUI thread:" + id);
    string text = state as string;
    mListBox.Items.Add(text);
}
}

編輯:

例如,run方法是由其他人(另一個開發人員)提供的,我需要將此方法作為UI線程(Main Thread或Form1類)中的另一個線程來運行,但是,每當我運行該線程時(run方法)我還需要使用UpdateUI方法更新ListBox mListBox

如果要在不實例化其父類的情況下執行它,則Run應該是靜態的。 另外, Run應該公開顯示,具體取決於您計划使用它的范圍。 例如

public static void Run(object state) { ... }

您是否想做這樣的事情?

Foo foo = new Foo();
var thread = new Thread(foo.Run);

(這是假設您將“運行”更改為“公開”)

暫無
暫無

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

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