在c#中从不同的类实例化线程方法

时间:2012-01-17 20:19:53

标签: c# multithreading synchronizationcontext

有人能指出我如何处理以下问题吗?基本上,我试图重用以下示例中的代码: 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线程(主线程或类Form1)中将此方法作为不同的线程运行,但是,每当我运行该线程时(运行方法)我还需要使用UpdateUI方法更新ListBox mListBox

2 个答案:

答案 0 :(得分:0)

如果你想在没有实例化它的父类的情况下执行它,那么

Run应该是静态的。此外,Run应公开,具体取决于您计划使用它的范围。 e.g。

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

答案 1 :(得分:0)

你想做这样的事吗?

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

(假设您将Run更改为public)