我只想在有空闲线程的情况下对并行线程执行操作。我不想等到线程可用(即我不想排队),否则如果没有线程可用,请在同一线程上运行操作。
那我做了什么:
public async Task<List<FaceAPI.Face>> DetectFace(string picture)
{
try
{
Stream img = new FileStream(picture, FileMode.Open);
var res = await detect.DetectWithStreamWithHttpMessagesAsync(img);
List<FaceAPI.Face> result = new List<FaceAPI.Face>();
for (int i = 0; i < res.Body.Count; i++)
{
result.Add(new FaceAPI.Face { Age = (double)res.Body[i].FaceAttributes.Age, Bald = res.Body[i].FaceAttributes.Hair.Bald > 0.5 ? true : false, Beard = res.Body[i].FaceAttributes.FacialHair.Beard > 0.5 ? true : false, Gender = res.Body[i].FaceAttributes.Gender.Value.Equals(Gender.Male) ? true : false, Glasses = res.Body[i].FaceAttributes.Glasses.Value.Equals(GlassesType.NoGlasses) ? false : true, Hair = res.Body[i].FaceAttributes.Hair.HairColor.ToString(), Moustache = res.Body[i].FaceAttributes.FacialHair.Moustache > 0.5 ? true : false,Rectangle=new System.Drawing.Rectangle { X = res.Body[i].FaceRectangle.Left, Y = res.Body[i].FaceRectangle.Top, Height = res.Body[i].FaceRectangle.Height, Width = res.Body[i].FaceRectangle.Width } });
}
return result;
}
catch (APIErrorException e)
{
Debug.WriteLine(e.Message);
return null;
}
catch (SerializationException e)
{
Debug.WriteLine(e.Message);
return null;
}
catch (ValidationException e)
{
Debug.WriteLine(e.Message);
return null;
}
}
这行得通吗? 还是有更好的方法?
答案 0 :(得分:0)
您可以使用
int worker = 0;
int io = 0;
ThreadPool.GetAvailableThreads(out worker, out io);
检查是否有大于0的数字, 然后:
Thread newThread = new Thread (()=>{DoSomething()});
newThread.Start();