它是对这个问题的跟进。
https://stackoverflow.com/questions/12260170/how-to-make-a-threadpool-to-be-nonblocking
我已经使用接口实现了它。我已经使用 Action/deleages 和使用接口使它成为非阻塞的。.net 中是否有任何其他方法可以使下面的代码成为非阻塞的???接口实现如下。在任何时候,我都应该只有三个函数 Main、FuncA 和 FuncB
如果有人可以提供帮助。将不胜感激。谢谢你。
using System;
using System.Threading;
namespace ConsoleApplication2
{
public interface IOperation
{
void CallBack(int i);
}
public class FuncBCalculation
{
public int N { get { return _n; } }
private int _n;
public int MyValue { get; set; }
public FuncBCalculation(int n)
{
_n = n;
}
// Wrapper method for use with thread pool.
public void FuncB(object context)
{
IOperation FuncBcallback = (IOperation)context;
Thread.Sleep(5);
MyValue = _n + 2;
FuncBcallback.CallBack(MyValue);
}
}
public class ActualClass : IOperation
{
int Finalvalue = 0;
public static IOperation MainThreadCallBack { get; set; }
public void FuncA(int input, int i, IOperation callback)
{
input += 1;
var f = new FuncBCalculation(input);
MainThreadCallBack = callback;
IOperation op = new ActualClass();
ThreadPool.QueueUserWorkItem(f.FuncB, op);
}
//Method for callback operation
public void CallBack(int i)
{
Finalvalue = i + 3;
if (MainThreadCallBack != null)
MainThreadCallBack.CallBack(Finalvalue);
}
}
public class ThreadPoolExample : IOperation
{
static void Main()
{
ActualClass actualCall;
const int TotalLoopCount = 1000;
int input = 11;
Console.WriteLine("launching {0} tasks...", TotalLoopCount);
for (int i = 0; i < TotalLoopCount; i++)
{
IOperation op = new ThreadPoolExample();
actualCall = new ActualClass();
actualCall.FuncA(input, i, op);
}
Console.ReadKey();
}
//Method for callback operation for the main thread
public void CallBack(int i)
{
Console.WriteLine("The final Result is {0}", i);
}
}
}