我需要在我的課程中執行「Invoke()」方法,其行爲與Control.Invoke()一樣。如何在自定義類型中實現Control.Invoke模擬?
所以,當我從從創建實例線程不同的線程我InvokableEntity類的實例的工作,我將能夠調用invokableEntity.Invoke(代表)和委託會在InvokableEntity的線程實例的上下文中執行是在創建。
是的,我讀過this問題,它不會幫助我=(
請看看他的代碼,它說明我嘗試實施事件處理程序描述的行爲(CustomProcessor_ProgressChanged方法應該從線程它被訂閱的情況下被執行,但我不能這樣做):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.ComponentModel;
using System.Windows.Forms;
namespace MultiThread
{
class Program
{
private static CustomProcessor customProcessor = new CustomProcessor();
static void Main(string[] args)
{
Console.WriteLine("Worker was run from thread: {0}", Thread.CurrentThread.ManagedThreadId);
customProcessor.ProgressChanged += new EventHandler(CustomProcessor_ProgressChanged);
Thread workerThread = new Thread(customProcessor.Process);
AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(null);
//SynchronizationContext context = SynchronizationContext.Current;
workerThread.Start(asyncOperation);
Console.ReadLine();
}
static void CustomProcessor_ProgressChanged(object sender, EventArgs e)
{
Console.WriteLine("Custom ProgressChanged was handled in thread: {0}", Thread.CurrentThread.ManagedThreadId);
}
}
class CustomProcessor
{
public event EventHandler ProgressChanged;
public void RaiseProcessChanged(object o)
{
Console.WriteLine("RaiseProgressChanged was handled in thread: {0}", Thread.CurrentThread.ManagedThreadId);
if (this.ProgressChanged != null)
{
this.ProgressChanged(this, EventArgs.Empty);
}
}
public void Process(object asyncOperation)
{
Console.WriteLine("CustomProcessor.Process method was executed in thread: {0}", Thread.CurrentThread.ManagedThreadId);
AsyncOperation asyncOperationInternal = (AsyncOperation)asyncOperation;
asyncOperationInternal.Post(this.RaiseProcessChanged, null);
//SynchronizationContext context = (SynchronizationContext) asyncOperation;
//context.Send(s => this.RaiseProcessChanged(null), null);
//this.RaiseProcessChanged(new object());
}
}
}
謝謝!
爲什麼沒有這個問題(+一些很好的答案)可以幫助你? – 2010-04-07 09:18:51
它只是不適合我,我不能得到可行的解決方案。調用總是在不同的線程中執行=( – Restuta 2010-04-07 09:25:12
顯示一些代碼 – 2010-04-07 09:27:51