Создание метода потока из другого класса в c # - PullRequest
0 голосов
/ 18 января 2012

Может кто-нибудь подсказать мне, как справиться со следующей проблемой?По сути, я пытаюсь повторно использовать код из следующего примера, найденного по адресу: 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);
}
}

РЕДАКТИРОВАТЬ:

например, метод запуска дал мне кто-то еще (другой разработчик), и мне нужно запустить этот метод как другой поток вМой поток пользовательского интерфейса (основной поток или класс Form1), однако, всякий раз, когда я запускаю поток (метод run), мне также необходимо обновлять ListBox mListBox, используя метод UpdateUI.

Ответы [ 2 ]

0 голосов
/ 18 января 2012

Вы хотите сделать что-то подобное?

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

(это предполагает, что вы изменили Run на public)

0 голосов
/ 18 января 2012

Run должен быть статическим, если вы хотите выполнить его без создания экземпляра родительского класса. Кроме того, Run должно быть открыто как общедоступное, в зависимости от того, как вы планируете его использовать. например,

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