微信小程序多线程使用(含视频讲解、源码)

简介

我们在开发微信小程序的时候,有时候会用到异步任务,如果把耗时任务放在主线程中,会导致主线程被阻塞,后面代码执行不了,界面会卡主、程序崩溃等问题。这时候就要用到多线程,来并发处理业务需求。

工具/原料

  • 微信开发者工具

  • 微信小程序APPID或可选测试号

  • 视频讲解:https://www.bilibili.com/video/BV11K41157RG?from=search&seid=7961875538802847306

  • 源码下载:https://pan.baidu.com/s/16iZpOmxTFAPXWgeGWz45Tg 提取码: 3xw7

方法/步骤

  1. 1

    在打开微信开发者工具,依次点项目 -> 新建项目,项目名称(随便写):workerDemo,目录:C:\Users\Administrator\WeChatProjects\workerDemo ,AppID:自己的AppID(不用发布,可用测试号),开发模式选“小程序”,然后点“新建”。

    微信小程序多线程使用(含视频讲解、源码)

    微信小程序多线程使用(含视频讲解、源码)

  2. 2

    打开项目根目录下的app.json文件,在最后一行追加

    "workers": "workers",记得上一行的最后要加逗号“,”,这是为了配置 Worker 代码放置的目录。

    微信小程序多线程使用(含视频讲解、源码)

    微信小程序多线程使用(含视频讲解、源码)

  3. 3

    在项目根目录下新建一个workers目录,workers目录下在新建两个目录分别是:request,response,然后在request里新建两个js文件:index.js、utils.js,在response目录下新建index.js文件。

    微信小程序多线程使用(含视频讲解、源码)

  4. 4

    在项目根目录下的workers/request/index.js里写上如下代码(worker线程核心代码):

     

    const utils = require('./utils')

     

      // 在 Worker 线程执行上下文会全局暴露一个 worker 对象,直接调用 worker.onMeesage/postMessage 即可

      //监听主线程向当前线程发送的消息的事件

      worker.onMessage(function (res) {

        console.log(res.msg)

      })

     

      var count = 0

      setInterval(function () {  //每秒定时像主线程发送消息

        console.log('这是worker内部线程打印的')

        //向主线程发送的消息

        worker.postMessage({

          msg: '来自于worker线程:' + count++

        })

      }, 1000)

    微信小程序多线程使用(含视频讲解、源码)

  5. 5

    在"pages/index/index"下的index.wxml文件加入如下代码:

     

    <!--index.wxml-->

    <view class="container">

      <view class="usermotto">

        <text class="user-motto">{{motto}}</text>

      </view>

    </view>

    微信小程序多线程使用(含视频讲解、源码)

  6. 6

    在"pages/index/index"下的index.js文件加入如下代码(主线程核心代码):

     

    //index.js

    //获取应用实例

    const app = getApp()

     

    Page({

      data: {

        motto: 'Hello Worker',

      },

      onLoad: function () {

        // 文件名指定 worker 的入口文件路径,绝对路径

        const worker = wx.createWorker('/workers/request/index.js');

        

        //向Worker线程发送的消息

        worker.postMessage({

          msg: '来自于主线程的消息'

        });

     

        //监听Worker线程向当前线程发送的消息的事件

        var that = this

        worker.onMessage(function(res){

          var resValue = res.msg

          console.log('------------------------------------------')

          console.log('这是主线程打印的')

          console.log(resValue) //打印res对象里的属性成员变量的值

          that.setData({  //绑定数据

            motto:resValue

          })

        });

        

        //worker.terminate()

      },

     

        

    })

    微信小程序多线程使用(含视频讲解、源码)

  7. 7

    点击编译运行,即可看到主线程和worker线程互相通信,传递信息。页面实时数据更新。子线程(worker线程)与主线程各做各的事,互不干扰。

    微信小程序多线程使用(含视频讲解、源码)

     

注意事项

  • 注意逗号问题,语句尾一般不加,否则报错。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
多线程 求质数 返回数组中的最大值 bool isPrime(long x) { if (x <= 1) return false; if (x == 2) return true; for (long i = 2; i <= ceil(sqrt((long double)x));i++) if (x%i == 0) return false; return true; } DWORD WINAPI findPrime(void* p) { long result=0; int l = stc(p)->lower, u = stc(p)->uper; int t_id=GetCurrentThreadId(); for (int i = l; i <= u;i++) if (isPrime(i)) { result++; } DWORD dReturn = WaitForSingleObject(mutex_mul_result_h, INFINITE); mul_result += result; ReleaseMutex(mutex_mul_result_h); //EnterCriticalSection(&gCRITICAL_SECTION_Printf); //printf("%d,%d,%d,%d\n", l, u, result,t_id); //fflush(stdout); //LeaveCriticalSection(&gCRITICAL_SECTION_Printf); return 0; } //dispatcher void dispatch() { DWORD Status; timer tm; tm.start(); //srand(time(NULL)); long step = STEP;//ceil(double(TEST/10)); handlenum = 0; for (int i = 1; i <= TEST;) { i += step; handlenum++; } handle_array=new HANDLE[handlenum]; Thread_id = new DWORD[handlenum ]; arg = new FP_ARG[handlenum]; InitializeCriticalSection(&gCRITICAL_SECTION_Printf); mutex_mul_result_h = CreateMutex(NULL, false, mutex_mul_result); handlenum = 0; for (int i = 1; i <= TEST;) { arg[handlenum].lower = i; arg[handlenum].uper = (i + step-1>TEST) ? TEST : i + step-1; handle_array[handlenum]=(HANDLE)CreateThread(NULL, 0, findPrime, &arg[handlenum], 0, &Thread_id[handlenum]); /*EnterCriticalSection(&gCRITICAL_SECTION_Printf); printf("lower:%d uper:%d thread_id:%d\n", arg[handlenum].lower, arg[handlenum].uper,Thread_id[handlenum]); LeaveCriticalSection(&gCRITICAL_SECTION_Printf);*/ i += step; handlenum++; } tm.stop(); Sleep(1000); printf("there are %d threads\n", handlenum); printf("the multithreads use %f msc\n", tm.read()); } //the number of 1-1000000 Primenumber void s_finePrime() { timer tm; long result = 0; tm.start(); for (int i = 1; i <= TEST; i++) if (isPrime(i)) result++; tm.stop(); printf("Single thread result is %d\n", result); printf("Single thread use %f msc\n", tm.read()); } int _tmain(int argc, _TCHAR* argv[]) { dispatch(); WaitForMultipleObjects(handlenum, handle_array, true, INFINITE);//不起作用 printf("the multithreads reslut is %d\n", mul_result); CloseHandle(mutex_mul_result_h); DeleteCriticalSection(&gCRITICAL_SECTION_Printf); s_finePrime(); system("pause"); return 0; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值