0

我有一些在另一个 AppDomain 中运行其方法(WorkFunction)的类。当我在控制台应用程序中使用它时,好的。但是当我尝试在单元测试框架(MSTest,Nunit)中运行相同的代码时,我得到以下错误:

System.IO.FileNotFoundException 未处理 HResult = -2147024894 消息 = 无法加载文件或程序集“FMEngine.Common.Tests,版本 = 1.0.0.0,文化 = 中性,PublicKeyToken = null”或其依赖项之一。找不到指定的文件。源 = mscorlib 文件名 = FMEngine.Common.Tests,版本 = 1.0.0.0,文化 = 中性 ...

错误在哪里?

在控制台中正常工作但在测试中出错的代码

ThreadWorkerTemplateWrapper twt = new ThreadWorkerTemplateWrapper(-1, new TimeSpan(0, 0, 1));
twt.Start();
Console.ReadLine();
twt.Stop();

源代码:

[Serializable] 
public class ThreadWorkerTemplate 
{
    #region non important code for question

                    private int _threadFlag;
    [NonSerialized] private readonly Thread _thread;
    [NonSerialized] private AppDomain _threadDomain;

    public ThreadWorkerTemplate(int timeout, TimeSpan joinTimeout)
    {
        IterationTimespan = timeout;
        JoinTimeout = joinTimeout;

        _threadFlag = 0;
        _thread = new Thread(ThreadHandler);
    }

    private bool IsDelaySpended(DateTime now, DateTime lastExecuted)
    {
        return (now > lastExecuted) 
               &&
               (now - lastExecuted).TotalMilliseconds > IterationTimespan;
    }

    private bool IsNothingDelay()
    {
        return IterationTimespan == -1;
    }

    public void Start()
    {
        if (null == _threadDomain)
            _threadDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());

        if (Interlocked.CompareExchange(ref _threadFlag, 1, 0) == 0)
            _thread.Start();
    }

    public void Stop()
    {
        bool exitByTimeout = false;

        // стопаем с одновременным измененем флага
        if (Interlocked.CompareExchange(ref _threadFlag, 0, 1) == 1)
            exitByTimeout = !_thread.Join(JoinTimeout);

        if (exitByTimeout)
        {
            AppDomain.Unload(_threadDomain);
            _threadDomain = null;
        }
    }

    public bool IsStarted { get { return Interlocked.CompareExchange(ref _threadFlag, 0, 0) == 1; } }
    public TimeSpan JoinTimeout { get; private set; }
    public int IterationTimespan { get; private set; }

    #endregion

    private void ThreadHandler()
    {
        DateTime lastExecuted = DateTime.MinValue;
        Func<bool> isAllowed =
            () =>
                {
                    DateTime now = DateTime.Now;
                    bool result = IsNothingDelay() || IsDelaySpended(now, lastExecuted);

                    if (result)
                        lastExecuted = now;

                    if (IterationTimespan != -1)
                        Thread.Sleep(1);

                    return result;
                };

        while (Interlocked.CompareExchange(ref _threadFlag, 0, 0) == 1)
        {
            if (isAllowed())
                _threadDomain.DoCallBack(new CrossAppDomainDelegate(WorkFunction));
        }
    }

    public void WorkFunction()
    {
        Thread.Sleep(60000);
    } 
}
4

0 回答 0