C# 是否建议在任务内循环?

C# 是否建议在任务内循环?,c#,.net,web-services,loops,task,C#,.net,Web Services,Loops,Task,是否真的建议在任务内循环 示例代码: public void doTask(){ Task.Factory.StartNew(() => { do{ // do tasks here.... call webservice }while(true till cancelled) }); } 任何答案都很好!:) 因为我的Web服务现在正在调用,内存消耗失控 所以我想问,任务内部的循环真的很好还是根本不被推荐 根据SLC

是否真的建议在任务内循环

示例代码:

public void doTask(){
    Task.Factory.StartNew(() => {
        do{
           // do tasks here.... call webservice
        }while(true till cancelled)
    });
}
任何答案都很好!:) 因为我的Web服务现在正在调用,内存消耗失控

所以我想问,任务内部的循环真的很好还是根本不被推荐

根据SLC的要求,代码如下:

CancellationTokenSource tokenSrc;
Task myTask;
private void btnStart_Click(object sender, EventArgs e)
{
    isPressed = !isPressed;



    if(isPressed)
    {
        tokenSrc = new CancellationTokenSource();
        myTask = Task.Factory.StartNew(() => 
        {
            do{
                checkMatches(tokenSrc.Token);
            }while(tokenSrc.IsCancellationRequested != true);
        }, tokenSrc.Token);
    }
    else {
        try{
            tokenSrc.Cancel();
            // Log to notepad
        }
        catch(Exception err){
           // Log to notepad
        }
        finally {
           if(myTask.IsCanceled || myTask.IsCompleted || myTask.isFaulted) {
               myTask.Dispose();
           }
        }

    }
}

private void checkMatches(CancellationTokenSource token) 
{
    try
    {
        if(!token.IsCancellationRequested)
        {
           //Create Endpoint...
           //Bypass ServCertValidation for test purposes
           ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate {return true;});
           using(WebServiceAsmx.SoapClient client = new....)
           {
               client.CheckResp response = client.chkMatch();
               // if's here for the response then put to logs
           }
        }
    }
    catch(Exception err)
    {
        // err.toLogs
    }
}

这样做很好,特别是当您的任务持续运行时,例如拾取消息队列

while (not shutting down)
   get next email to send
   if exists next email to send
      send
   else
      wait for 10 seconds
wend
如果你需要取消它,确保你有办法离开,就像你用旗子做的那样,你应该没事

关于网络服务:

重复调用webservice应该没有问题,也不应该导致任何内存峰值。但是,您应该确保您的初始化代码不在循环中:

坏的

根据您的Web服务,创建一个批处理操作可能更为理想,例如,如果您的服务是HTTP,那么重复访问它会带来大量开销。持久TCP连接可能更好,因为它可能会创建和销毁许多对象来进行调用

比如说

速度慢,开销大:

myRecords = { cat, dog, mouse }

foreach record in myRecords
    webservice check record
endforeach
更快:

myRecords = { cat, dog, mouse }
webservice check [myRecords] // array of records is passed instead of one by one
调试:最有可能的风险是任务没有得到正确的处理-您可以将此添加到您的方法中进行调试吗

myTask = Task.Factory.StartNew(() => 
        {
            Console.Writeline("Task Started");
            do{
                checkMatches(tokenSrc.Token);
                Thread.Sleep(10); // Some pause to stop your code from going as fast as it possibly can and putting your CPU usage to 100% (or 100/number of cores%)
            }while(tokenSrc.IsCancellationRequested != true);
            Console.Writeline("Task Stopped");
        }
根据您是否有控制台,您可能必须更改它,使其写入文件或类似文件


然后运行它,确保只创建了一个任务。

它是否也适用于Web服务?就像在收到响应后,它会再次循环回调用webservices?这是调用webservices的一个糟糕的例子。在循环中初始化它会导致内存峰值吗?因为我一直在经历它,它让我非常头疼。如果你重复创建对象,这很可能是真的。如果你编辑你的问题并发布你的实际代码,你会更容易发现它可能在哪里。很酷,看起来不错,但是作为检查,你能在你的任务中添加一些调试吗?我已将调试添加到我的答案中以尝试。你还应该放一个
线程。Sleep(10)进入你的循环,否则它会将你的CPU使用率提高到100%,我怀疑内存消耗不是在你的代码中,而是在Web服务中。我看不出你上面的代码有任何错误。
myRecords = { cat, dog, mouse }
webservice check [myRecords] // array of records is passed instead of one by one
myTask = Task.Factory.StartNew(() => 
        {
            Console.Writeline("Task Started");
            do{
                checkMatches(tokenSrc.Token);
                Thread.Sleep(10); // Some pause to stop your code from going as fast as it possibly can and putting your CPU usage to 100% (or 100/number of cores%)
            }while(tokenSrc.IsCancellationRequested != true);
            Console.Writeline("Task Stopped");
        }