我需要在我的课程中执行“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