How can I do 2 tasks at the same time? - c#

Im trying to get a function and a return at go at the same time, or i need the function to run after the return.
private void GiveBackInput(string s)
{
Thread.Sleep(125);
SendKeys.SendWait(s);
}
private bool idontrememberthisname(string hexcode){
... if (...)
{
GiveBackInput("A");
return true;
}
//i need it to be like this
... if (...)
{
return true;
GiveBackInput("A");
}}
edit: forgot to put that the if statement is in a different method

You need to use a new task or new thread.
https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=netframework-4.8

Related

Wrap Function / Avoid repeating coid

I'm new to c# and I have a (for me:) complex application with a grpc-interface.
I have about 20 (and rising) different functions where I pass different parameters and return different types:
private async Task<VersionOfInterfaceReply> Function1()
{
...
}
private async Task<ReturnInfoReply> Function2(
List<NozzleToChange> nozzlelist,
SideType side = SideType.Right,
UInt32 processingarea = 1)
{
...
}
afterwards I want call,get,evaluate these testresults and repeat some functions.
{
ResetTestResult();
result = await Function1();
if (result.success = true) { testresult.TestLog += $"message with variables of result\n"; }
TestPassed(result);
ResetTestResult();
result = await Function2(x,y,z);
if (result.success = true) { testresult.TestLog += $"{result.xy} message with variables of result\n"; }
TestPassed(result);
}
result is already a dynamic variable (if you know better ways let me know)... but my question is following:
How can I get rid of the ResetTestResult(); and Testpassed(result) with some kind of wrapping my functions?
Is this even possible with different output/parameter types and different amount of parameters
I would like to have something like:
privat async Task? / or void CallFunction(Method givenMethod, string message)
{
ResetTestResult();
result = await givenMethod();
if (result.success = true) { testresult.TestLog += $""+message +" with variables of result\n"; }
TestPassed(result);
}
and call this like this:
{
...
CallFunction(Function1(),"message1");
CallFunction(Function2(x,y,z),"message2 {variable2}");
...
}
I tried understanding delegates, func, and actions, but im not really sure if this works for me. And another problem is the async part...
If you need any further information let me know.
thanks for your help in advance
kind regards
chris
Assuming VersionOfInterfaceReply and ReturnInfoReply implement an interface, such as:
interface IReply
{
bool Success { get; }
}
You could write your method like this:
private async Task CallFunction<T>(Func<Task<T>> givenMethod, Func<T, string> message)
where T : IReply
{
ResetTestResult();
T result = await givenMethod();
if (result.Success) { testresult.TestLog += message(result); }
TestPassed(result);
}
And use as follows:
await CallFunction(Function1, x => "message1");
await CallFunction(() => Function2(x, y, z), x => $"message2 {x.Variable2}");
To call methods with arguments, you can create a closure using a lambda expression.
Working example

Asynchronous coroutine handling in unity

I have used a coroutine to do a backend service call to retrieve the player categories in my category.cs file:
public override void OnEnter(Page p)
{
backend = globalScriptObject.GetComponent<IBackendController>();
items.Clear ();
StartCoroutine (backend.GetPlayerProfile ( profile =>{
this.maxSelectableItems = Mathf.CeilToInt(profile.level/10+1);
if(this.maxSelectableItems == 7) maxSelectableItems = int.MaxValue;
DisableSelections();
}));
GetPlayerProfile (In a different class which has been called using instance backend of that class)
public IEnumerator GetPlayerProfile(System.Action<Profile> callback){
yield return GetPlayerProfile (callback, false);
}
Issue:
Since i am using an external service call,sometimes the player profile is uploaded with a delay.
I need to make sure that the startcoroutine is finished with result before the rest of the lines of code is executed.
I tried creating the following class after searching from the internet which can make sure the couroutine call is finished before the rest of the lines are executed:
{
StartCoroutine(FinishFirst(5.0f, DoLast));
}
IEnumerator FinishFirst(float waitTime, Action doLast) {
print("in FinishFirst");
yield return new WaitForSeconds(waitTime);
print("leave FinishFirst");
doLast();
}
void DoLast() {
print("do after everything is finished");
print("done");
}
But how can i use the above in my source code is what i would need suggestions from the community.
Also can i do something like yield return waitForSec(Float) in the GetPlayerProfile method?
Thanks !!
Try using WaitUntil.
https://docs.unity3d.com/ScriptReference/WaitUntil.html
Something like this:
IEnumerator GetProfile(){
var profile = null;
yield GetPlayerProfile((p) => {profile = p});
yield WaitUntil(p != null);
this.maxSelectableItems = Mathf.CeilToInt(profile.level/10+1);
if(this.maxSelectableItems == 7) maxSelectableItems = int.MaxValue;
DisableSelections();
}
And then...
StartCoroutine(GetProfile);

C# - Try something twice if if-statement is true

I have a code parsing a website and adding some values to a list. Sometimes I need to parse the website two times and add the second parsevalues to the same list.
This is some of the code:
public async Task<IEnumerable<Info>>....
{
var values = new List<Info>();
var request = something;
var request_rewritten = rewritten request to run the second time;
......
if request contains something do all the under two times. Both for the request and the rewritten request and add it to result.
......
var response = await RequestBytes(request);
var results = Encoding.GetEncoding("iso-8859-1").GetString(response.Content);
_fDom = results;
try
{
do something and a lot of code
......
values.Add(result);
return result
}
}
If request contains something I need try try a second time. Both for the original request and the rewritten request and add both to the result. Can this be done?
You can follow this pattern. Add an additional parameter to your method indicating retries remaining.
void DoSomething(arg1, arg2, int retriesRemaining = 0)
{
try
{
DoWork();
}
catch
{
if (retriesRemaining) DoSomething(arg1, arg2, --retriesRemaining);
}
}
I suppose if you want to avoid writing a method (which is the best answer to your question) you can use a flag:
bool bRunAgain = true;
while (bRunAgain)
{
// Your logic, check result and see if you need to run it again
if (your condition to run again == false)
{
bRunAgain = false;
}
}
Here is a common solution. Pass an action to this method and specify retries count
public bool ExecuteWithRetry(Action doWork, int maxTries=1) {
for(var tryCount=1; tryCount<=maxTries; tryCount++){
try{
doWork();
} catch(Exception ex){
if(tryCount==MaxTriex){
Console.WriteLine("Oops, no luck with DoWork()");
return false;
}
}
return true;
}
}
so in your method
void Something(){
....
if(ExecuteWithRetry(()=>NotTrustyMethod(), 2)) {
//success
} else {
//fail
}
}
void NotTrustyMethod(){ ...}
This solution you can use for any case where you need retry option for methods with any type of arguments (or without them)

can a value be stored in variable returned by a function called as a parameter

Hi I was integrating facebook SDK in unity and basically I worked in java earlier and I am new to c# script and a question came to my mind.
I have searched a lot found nothing, may be my searching query is good enough or not but my question is ...
as a function FB.init called here
void Awake ()
{
FB.Init(InitCallback, OnHideUnity);
}
here when init function will be called it will call InitCallBack and OnHideUnity functions and both are returning void these are used form facebook-unity-sdk docs
private void InitCallback ()
{
if (FB.IsInitialized) {
// Signal an app activation App Event
FB.ActivateApp();
// Continue with Facebook SDK
// ...
} else {
Debug.Log("Failed to Initialize the Facebook SDK");
}
}
private void OnHideUnity (bool isGameShown)
{
if (!isGameShown) {
// Pause the game - we will need to hide
Time.timeScale = 0;
} else {
// Resume the game - we're getting focus again
Time.timeScale = 1;
}
}
My question is if I call a function like this and that function return something e.g String and I want wanted to store it something like this
String result="";
SomeFunctions(FunctionOne,result=FunctionTwo);
String FunctionTwo()
{
return "a String";
}
Is this possible?
Is there any way to get value returned by such function call?
Or is this possible that a function that returns value can be called in this way?
It seems like you are confusing a delegate for a function expression. The delegate will have no return value until it is invoked as a function.
void SomeFunction(Func<string> func) {
var result = func(); // only here will the function return value be accessible
Console.WriteLine(result);
}
SomeFunction(() => "test");
Although you do not have access to the return value of the function, the delegate could assign a variable you choose inside it's method body, instead of using it's return value:
string result;
SomeFunction(() => {
result = "test";
return result;
});
// result would now contain "test"
I am not sure what you want to achieve here, but you could use out to change the reference of the parameter.
string result="";
MyMethod(out result);
Debug.Log(string.Format("Result: {0}", result));
void MyMethod(out string pValue)
{
pValue = "my changed value";
}
The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.
https://msdn.microsoft.com/en-us/library/t3c3bfhx.aspx
But in a case like this, you could just return the correct value. In the example below its not even worth passing the parameter since we are not using it.
string result = MyMethod(result);
string MyMethod(string pValue)
{
pValue = "My changed value";
return pValue;
}

C# How to implement flag messaging system between two methods in a business logic class of a WCF app?

I have two methods in a C# business logic class. I need a flag mechanism so that one method can update the flag and the other method will react when the flag is updated. Below I will paste my situation, which is very simple:
// BusinessLogic.cs
bool photoResizingFinished = false;
public int SavePhoto() {
while (!photoResizingFinished) {
System.Threading.Thread.Sleep(100);
Trace.TraceInformation("PhotoResizingWorkerRole has not finnished yet.");
} }
public bool UpdateStatus(bool statusUpdate) {
photoResizingFinished = statusUpdate;
return true;
}
The two methods above live in the same class BusinessLogic.cs.
The only thing I need is to be able to have SavePhoto() react when
the bool photoResizingFinished is updated by UpdateStatus(bool statusUpdate)
You can use the class as a webservice and implement callback function that called when the ws finishes its work.
example code:
<script>
var timerID = setTimeout(CallWS, 1000)//call a js func which calls the WevService
function CallWS()
{
clearTimeout(timerID)//to stop the calling...
WSClassName.WSFuncName(param1,param2,....,callBackSuccess,callBackFailur)
///the param1,param2 are according to the parameter the function is expected to get.
}
function callBackSuccess(result,eventArgs)
{
//When the WS function finished successfuly
//**set flag to true.**
}
function callBackFailur(result,eventArgs)
{
//when error occured in the WS function
alert(result.get_message()).
}
</script>
Let me know if you need more help...
goodluck!
You could try using the Task class from .Net 4. It allows you to queue up tasks, so your SavePhoto() code would wait until the PhotoResizing() method finished.
Here's a nice article on the Task namespace if you want more details: http://www.codethinked.com/net-40-and-systemthreadingtasks
using System.Threading.Tasks;
public void SavePhoto(CancellationTokenSource taskCancellationTokenSource){
// preliminary code
// start resize
Task resizeTask = Task.Factory.StartNew( ResizePhoto, taskCancellationTokenSource ) ;
// queue up final save method
Task finalTask = resizeTask.ContinueWith(t => {
if (!t.IsFaulted && !t.IsCancelled){
FinishSaving();
}
});
// Wait for everything to finish
finalTask.Wait(taskCancellationTokenSource);
}
public void ResizePhoto(){
// code
}
public void FinishSaving(){
// code
}
I'd change the bool like this:
bool _photoResizingFinished=false;
bool photoResizingFinished
{
get{return _photoResizingFinished;}
set
{
if(value) SavePhoto();
_photoResizingFinished=value;
}
}
Or, you can make UpdatePhoto() call SavePhoto() after updating the bool. Might be a better solution.
Maybe I have found a solution to my problem using a Multithreaded Singleton
http://msdn.microsoft.com/en-us/library/ff650316.aspx
Here are some attempts of implementation:
http://forums.asp.net/t/1783765.aspx/2/10?How+to+have+two+methods+of+the+same+class+flag+to+eachother+
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/abd53523-658b-442a-bac0-1c74c1d90a90
I don't understand the mecanics of this myself totally, but I hope it's ok.

Categories