Anyway, to finish the delegate, if I no longer care about the results?

I have a piece of code that is looking for several third-party APIs. My search queries are divided into 2 groups based on search criteria. I start both searches, because each search is done in a rather timely manner, but if the first group of queries leads to a match, I do not want to wait until the second group of searches is finished. So basically what I have:

Dictionary<string, string> result = null;
NameSearchDelegate nameDel = new NameSearchDelegate(SearchByName);
IAsyncResult nameTag = nameDel.BeginInvoke(name, null, null);
if(!string.IsNullOrWhiteSpace(telNum))
{
    result = SearchByTelNum(telNum);//Will return null if a match is not found
}
if(null == result)
{
    result = nameDel.EndInvoke(nameTag);
}
//End the delegate to prevent memory leak
//else
//{
//    nameDel.EndInvoke(nameTag)
//}
return result;

So, I want to start SearchByName before I call SearchByTelNum if it does not find a match, however, if it finds a match, I do not want to wait for SearchByName to complete before returning a match. Is there a way to simply end or cancel this delegate if I no longer need its result?

+5
2

System.ComponentModel.BackgroundWorker. , , , . , , :

Dictionary<string, string> telResult = null,
                           nameResult = null;

BackgroundWorker bw = new BackgroundWorker();
bw.WorkerSupportsCancellation = true;
bw.DoWork += (obj, e) => nameResult = SearchByName(name, bw);
bw.RunWorkerAsync();

if(!string.IsNullOrWhiteSpace(telNum))
    telResult = SearchByTelNum(telNum);//Will return null if a match is not found

if(telResult != null)
{
    bw.CancelAsync;
    return telResult;
}

bool hasTimedOut = false;
int i = timeOutCount;
while (bw.IsBusy && !hasTimedOut)
{
    System.Threading.Thread.Sleep(500);
    if (0 == --i) hasTimedOut = true;
}

return nameResult;

, , , SearchByName , bw.CancellationPending true, . CancelAsync , , .

while(bw.IsBusy) System.Threading.Thread.Sleep(500)

, SearchByName - , . , , -, . , bw.IsBusy 0,5 , timeOutCount/2 .

, , .

+1

, abortable parameter

public class AbortableParameter<T>
{
    public T Parameter { get; private set }
    public bool ShouldAbort { get; set; }
    public AbortableParameter(T parameter)
    {
        Parameter = parameter;
        ShouldAbort = false;
    }
}

, , ; true, . ShouldAbort , true.

, , .

, set ShouldAbort , true, , .

0

All Articles