I have two methods using in Main method like this
public bool isBadMethod()
{
bool isBad = Method1();
if(isBad) return true;
else return Method2();
}
bool Method1() { ..... return true or false }
bool Method2() { ..... return true or false }
If any of Method1 or Method2 returning true no need to check for other method we can return MainMethod as true. But if first method returns false then need to check for second method and finally return whatever second method returns. Here Method1 and Method2 are time consuming methods. Can I use asynchronous programming on these methods. Help how to do. (I'm using .net 4.0)
You could just make use of short-circuiting of expressions:
bool val = Method1() || Method2();
If Method1
returns true
, it doesn't bother with the second method.
Obviously, if the method calls are expensive then continue with the task route, as this isn't parallel execution. I'm just posting this in case it's an XY Problem.
Method2
. This also does cancellation. I am not sure if the types used are best practice as my experience with this is patchy, but it gets the job done in my sandbox:
internal class Program
{
private static void Main(string[] args)
{
var cm2 = new CancellationTokenSource();
var m1 = Task.Factory.StartNew(() => Method1());
var m2 = Task.Factory.StartNew(() => Method2(cm2.Token), cm2.Token);
var val = m1.Result || m2.Result;
cm2.Cancel();
Console.WriteLine(val);
Console.ReadLine();
}
private static bool Method1()
{
Thread.Sleep(1000);
Console.WriteLine(1);
return true;
}
private static bool Method2(CancellationToken token)
{
Thread.Sleep(3000);
if (token.IsCancellationRequested)
return false;
Console.WriteLine(2);
return true;
}
}
As Matthew Watson points out in the comments, the cancellation token needs to be used by Method2
in order to actually "cancel". In my example, it simply stops the printing of the number and returns early.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments