如何在不同的域中异步执行代码?
例如,我有一个方法:
public void DoSomething()
{
// do something
}
我想在10个不同的域中执行它,如下所示:
for (int i = 0; i < 10; i++)
{
AppDomain domain = AppDomain.CreateDomain("NewDomain - " + i);
domain.ExecuteAsync(DoSomething);
}
答案 0 :(得分:1)
我用这种方法解决了我的任务:
for (int i = 0; i < options.NumberOfThreads; i++)
{
tasks[i] = Task.Factory.StartNew(() =>
{
using (Isolated<TesterInvoker> isolated = new Isolated<TesterInvoker>())
{
isolated.Value.Invoke();
}
});
}
private class TesterInvoker : MarshalByRefObject
{
public void Invoke()
{
// do something
}
}
private class Isolated<T> : IDisposable
where T : MarshalByRefObject
{
private AppDomain _domain;
private T _value;
public Isolated()
{
Type type = typeof(T);
_domain = AppDomain.CreateDomain("Isolated:" + GetHashCode(),
null, AppDomain.CurrentDomain.SetupInformation);
_value = (T)_domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
}
public T Value
{
get
{
return _value;
}
}
public void Dispose()
{
if (_domain != null)
{
AppDomain.Unload(_domain);
_domain = null;
}
}
}