使用主线程

时间:2015-09-29 12:03:14

标签: c# .net multithreading thread-safety

我在我的测试类中初始化并启动了五个线程:

[Test]        
public void ReportGeneratorFiveThreadTest()
{
    var threads = new List<ReportGeneratorThread>();
    var logger = new Log4NetLogger(typeof(ReportGeneratorThreadTest));

    for (var i = 0; i < 5; i++)
    {
        var estimatedReportSize = EstimatedReportSize.Normal;
        var thread = new ReportGeneratorThread(logger, new ReportGenerator(20), estimatedReportSize, new ManualResetEvent(false));
        thread.Name = string.Format("ReportGeneratorThread{0}", i);
        threads.Add(thread);
    }
    threads.ForEach(t => t.Start());          
}

我通过在ReportGeneratorThread类中调用以下方法来启动所有线程:

public void Start()
    {
        this.running = true;
        this.t = new Thread(this.GenerateReport());
        this.t.SetApartmentState(ApartmentState.STA);
        this.t.Start();
    }

为了执行操作,它调用GenerateReport()方法:

public void GenerateReport()
    {
        var didwork = false;
        try
        {
            didwork = this.reportGenerator.GenerateReport(this.estimatedReportSize);
        }
        catch (Exception e)
        {
            this.log.LogError(ReportGenerator.CorrelationIdForPickingReport, string.Format(CultureInfo.InvariantCulture, "System"), string.Format(CultureInfo.InvariantCulture, "Error during report generation."), 0, e);
            this.doneEvent.Reset();
            Debug.WriteLine("Thread is aborted !!!");
        }
        finally
        {
            if (!didwork)
            {
                Thread.Sleep(Settings.Default.ReportGenerationInterval);
            }
        }
    }

我的目的是一旦所有五个线程中的一个线程被中止(GenerateReport()方法中抛出一个异常)并在之后在我的主线程中重新启动它,就通知我的主线程。我已经尝试过为此目的使用ManualResetEvent,但似乎它不是用于此目的的正确类。有什么方法吗?

0 个答案:

没有答案