logo
down
shadow

Is this incorrect way to implement asynchronous method


Is this incorrect way to implement asynchronous method

By : user2955596
Date : November 22 2020, 10:40 AM
around this issue If you implement your asynchronous method correctly you don't need to run it in a separate thread. Make the return type Task as void returning async methods swallow all exceptions and are usually reserved for event handlers only. Instead of Thread.Sleep use await Task.Delay. The former blocks a thread, the later waits asynchronously without blocking a thread. For best practices, see this article.
code :
private static async Task PingX()
{
    while(_ping)
    {
        await PingAll();
        await CheckWhoAreDisConnected();
        await Task.Delay(1000);
    }
}
public static Task BeginListening()
{
   Online = new Online(50);
   Listnerobj= new TcpListener(System.Net.IPAddress.Any, port);
   Listnerobj.Start();
   await PingX();
 }


Share : facebook icon twitter icon
How can I implement asynchronous pattern for save method in C#?

How can I implement asynchronous pattern for save method in C#?


By : user2592011
Date : March 29 2020, 07:55 AM
wish helps you I am working on a project where I am implementing a SaveSettings method which saves lot of settings to a xml file. , The Save() of XDocument can be implemented as:
code :

public void Save(string xmlFilePath)
{
    Thread thread = new Thread(new ParameterizedThreadStart(SaveSettings));
    thread.Start(xmlFilePath);
}

private void SaveSettings(object data)
{
    string xmlFilePath;
    if ((xmlFilePath = data as string) != null)
    {
        this.SaveSettingsFile(xmlFilePath);
    }
}

private void SaveSettingsFile(string xmlFilePath)
{ 
    // Save the file contents
}
Using IObservable to implement an asynchronous method

Using IObservable to implement an asynchronous method


By : user2901255
Date : March 29 2020, 07:55 AM
it should still fix some issue Firstly it's absolutely fine to return an IObservable to implement asynchronous methods.
Secondly, if it's the DoApiRequest method that kicks off the process that emits values through Messages, you could subscribe to messages first before calling the method using CreateWithDisposable
code :
public IObservable<bool> DoAsyncRequest()
{
    return Observable.CreateWithDisposable<bool>(observer =>
        {    
            var disposable = this.api.Messages
                .Where(m => m.RequestId == requestId)
                .Take(1)
                .Timeout(DefaultTimeout);
                .Subscribe(observer);

            int requestId = GenerateRequestId();

            this.api.DoApiRequest(requestId);

            return disposable;

        });
}
Is this correct way to implement task-based asynchronous method?

Is this correct way to implement task-based asynchronous method?


By : Дмитрий Булыка
Date : March 29 2020, 07:55 AM
wish helps you As others have mentioned in the comments, the entire point of background threads is to do background work. In your example, there is no background work; the entire background delegate is just sending work to the UI thread.
If this is actually representative of your code, you may as well just do it on the UI thread directly:
code :
private void Add()
{
  for (int i = 0; i < 40000; i++)
    this.listBox1.Items.Add(i);
}
private async Task AddAsync()
{
  IProgress<int> progress = new Progress<int>(x => this.listBox1.Items.Add(x));
  await Task.Run(() =>
  {
    for (int i = 0; i < 40000; i++)
    {
      int value = i; // TODO: replace this with the long-running create-item code.
      progress.Report(value);
    }
  });
}
angular2 Observable: How to wait asynchronous result and return another asynchronous method

angular2 Observable: How to wait asynchronous result and return another asynchronous method


By : Ismail Elmogy
Date : March 29 2020, 07:55 AM
will help you I have to resolve a problem with asynchronous calls. Scenario: , If you take a look to your method definition :
code :
private makeReservation(reservationDto: ReservationDTO): Observable<SaveResponse>
private makeReservation(reservationDto: ReservationDTO): Observable<SaveResponse>{
  return this.reservationHttpService.send3DRequest(reservationDto.threeDQueryDetails)
private makeReservation(reservationDto: ReservationDTO): Observable<SaveResponse>{
  return this
    .reservationHttpService
    .send3DRequest(reservationDto.threeDQueryDetails)
    .switchMap(response => {
        let result;

        if(successResponse.enrolled === 'Y') {
          reservationDto.transRef = successResponse.transactionRef;
          reservationDto.acsUrl = successResponse.acsUrl;
          reservationDto.paReq = successResponse.paReq;

          result = this.reservationHttpService.save(reservationDto);
        }

        else {
          reservationDto.transRef = successResponse.transactionRef;
          result = this.reservationHttpService.save(reservationDto);
        }

        return Observable.of(result);
      }
    )
    .catch(err => {
      // handle your error here
      return Observable.of({});
    })
}
How to Implement Asynchronous Queue to run Method in Symfony 3

How to Implement Asynchronous Queue to run Method in Symfony 3


By : Jan Cardozo
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further This is something you can easily do with enqueue bundle. Just a few words on why should you choose it:
It supports a lot of transports from the simplest one (filesystem) to enterprise ones (RabbitMQ or Amazon SQS). It comes with a very powerful bundle. It has a top level abstraction which could be used with the greatest of ease. There are a lot more which might come in handy.
code :
<?php
namespace Acme;

use Enqueue\Client\ProducerInterface;

class AddUserLTVService
{
    /**
     * @var ProducerInterface
     */
    private $producer;

    /**
     * @param ProducerInterface $producer
     */
    public function __construct(ProducerInterface $producer)
    {
        $this->producer = $producer;
    }

    public function addUserLTV( $userID, $addLTV )
    {
        $this->producer->sendCommand('add_user_ltv', [
            'userId' => $userID, 
            'ltv' => $addLTV]
        );
    }
}
services:
    Acme\AddUserLTVService: 
        arguments: ['@enqueue.producer']
<?php
namespace Acme;

use Enqueue\Client\CommandSubscriberInterface;
use Enqueue\Psr\PsrContext;
use Enqueue\Psr\PsrMessage;
use Enqueue\Psr\PsrProcessor;
use Enqueue\Util\JSON;

class AddUserTVAProcessor implements PsrProcessor, CommandSubscriberInterface
{
    public function process(PsrMessage $message, PsrContext $context)
    {
        $data = JSON::decode($message->getBody());

        $userID = $data['userID'];
        $addLTV = $data['ltv'];

        // do job

        return self::ACK;
    }

    public static function getSubscribedCommand()
    {
        return 'add_user_ltv';
    }
}
services:
    Acme\AddUserTVAProcessor: 
        tags:
            - {name: 'enqueue.client.processor'}
./bin/console enqueue:consume --setup-broker -vvv
Related Posts Related Posts :
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • Check what needs full trust
  • What is the execution order of an MVC Razor view/layout
  • Table designer (Entity Framework) is too resource intense
  • How to clean up an exception string so it can be displayed via Javascript Alert?
  • Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)
  • C# api responce and request
  • Dynamodb putitem function not working properly
  • theme in windows phone(light or dark) using c#
  • Backup attached database file(.mdf) using c# and SQL Server
  • What is 'TextFile' and where it is uses in WPF project
  • Using same alias for multiple namespaces
  • how to move mails into separate folders
  • Multithreaded Uploader
  • Memory fragmentation?
  • C# correct exception handling
  • "Could not open macro storage" when accessing using file on another machine
  • How to access other directories of hosted server
  • C# Jagged Array check if value exists/true
  • Why can't I type Clone() properly?
  • exception on accessing dictionary from list
  • Getting the immediate response from server without waiting to 200 message
  • Why am I getting exception Directory Is Not empty?
  • Could not load file or assembly 'CefSharp.dll' or one of its dependencies
  • Sending Email By Using C# in unity3D?
  • Correct usage of await async in webapi
  • Program update code issue
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org