如何返回线程结果

时间:2015-11-30 10:26:14

标签: c# wpf multithreading linq wcf

我如何回归" var T "喜欢" var结果"在下面的例子中(代码注释)在我创建的新线程中?

public QuoteResult GetQuote(QuoteData Data)
{
    using (TruckDb db = new TruckDb())
    {
        const int stackSize = 8000000;
        var T = new Thread(() => CalculateRates(db, Data), stackSize);
        T.Priority = ThreadPriority.Highest;
        T.Start();
        T.Join();

        //var result = CalculateRates(db, Data);
        //return result; //Example of how I want it in the new thread created above
    }
}

我的 CalculateRates 方法编码:

public QuoteResult CalculateRates(TruckDb db, QuoteData data)
{
    var result = new QuoteResult
    {
        Successful = false,
        Data = data
    };

    List<QuoteItemSectionGroup> quoteItems = new List<QuoteItemSectionGroup>();

    var quoteItem = new QuoteItem
    {
        ChassisModel = db.ChassisModel.Find(data.ChassisId),
        ChassisManufacturer = db.ChassisManufacturer.Find(data.ChassisManufacturerId),
        BodyType = db.BodyTypes.Find(data.BodyTypeId),
        //...10 lines more
    };

    //...unnecessary to see codes and calculations...

    result.QuoteItem = quoteItem;
    result.Successful = true;
    return result;
}

我只需要在新线程中运行我的CalculateRates方法来增加堆栈大小。如果您需要更多代码或信息,请不要犹豫。谢谢!

1 个答案:

答案 0 :(得分:3)

最直接的方法是

QuoteResult qr = null;
var T = new Thread(() => qr = CalculateRates(db, Data), stackSize);
T.Priority = ThreadPriority.Highest;
T.Start();
T.Join();
return qr;

或者,在此上下文中,另一种方法是使用out参数而不是函数返回值。如果您需要返回多个值,这将特别有用。

public void CalculateRates(TruckDb db, QuoteData data, out QuoteResult qrResult)
{
    qrResult= new QuoteResult
    {
        Successful = false,
        Data = data
    };    

    //...unnecessary to see codes and calculations...

    qrResult.QuoteItem = quoteItem;
    qrResult.Successful = true;        
}

然后打电话给:

 QuoteResult qr = null;
 var T = new Thread(() => CalculateRates(db, Data, out qr), stackSize);
 T.Priority = ThreadPriority.Highest;
 T.Start();
 T.Join();
 return qr;

在这两种情况下,null初始化都是必需的,因为编译器无法跨线程边界查看以确定实际已分配了值。例如,如果没有.Join调用,很可能尚未分配值,因此您必须明确。